"use client";

import { FiMail } from "react-icons/fi";
import { useEffect, useState } from "react";
import Button from "../../ui/Button";
import { useModal } from "../../../lib/modal-system/ModalContext";
import useResendEmail from "../../../hooks/features/auth/resend-email/useResendEmail";

const COOLDOWN_SECONDS = 60;

export default function CheckEmailForPasswordReset({
  email = "john@example.com",
}) {
  const { handleResendEmail, loading } = useResendEmail();
  const { openModal } = useModal();

  const [cooldown, setCooldown] = useState(COOLDOWN_SECONDS);

  useEffect(() => {
    if (cooldown <= 0) return;
    const timer = setTimeout(() => setCooldown((prev) => prev - 1), 1000);
    return () => clearTimeout(timer);
  }, [cooldown]);

  const onResend = async () => {
    if (cooldown > 0 || loading) return;
    try {
      await handleResendEmail({ email });
      setCooldown(COOLDOWN_SECONDS);
    } catch (error) {}
  };

  const isDisabled = loading || cooldown > 0;

  return (
    <div className="text-center">
      {/* Icon */}
      <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-[#E5D8FF] text-link-1 md:h-16 md:w-16">
        <FiMail size={24} />
      </div>

      {/* Heading */}
      <h2 className="mt-7 font-heading text-xl font-semibold text-heading">
        Check your email
      </h2>

      {/* Description */}
      <p className="mx-auto mt-5 max-w-[320px] font-body text-base leading-8 text-text">
        We sent a reset link
        <br />
        to <span className="font-medium text-link-1">{email}</span>.
      </p>

      {/* CTA */}
      <Button disabled={isDisabled} className="mt-8 w-full" onClick={onResend}>
        {loading
          ? "Resending..."
          : cooldown > 0
            ? `Resend in ${cooldown}s`
            : "Resend Email"}
      </Button>

      {/* Back */}
      <p className="mt-8 font-body text-base text-heading">
        <button
          type="button"
          onClick={() => openModal("FORGOT_PASSWORD", {})}
          className="cursor-pointer font-medium text-link-1"
        >
          Go Back
        </button>
      </p>
    </div>
  );
}
