"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";
import { useAppSelector } from "../../../hooks/useAppRedux";

const COOLDOWN_SECONDS = 35;

export default function CheckEmailForVerify({ email = "john@example.com" }) {
  const { handleResendEmail, loading } = useResendEmail();
  const accessToken = useAppSelector((state) => state.user.token);
  const { openModal, closeModal } = 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've already sent a verification email. If it hasn't arrived yet, check
        your spam folder or resend it after a moment.
        <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 */}
      {!accessToken ? (
        <p className="mt-8 font-body text-base text-heading">
          {/* Wrong email?{" "} */}
          <button
            type="button"
            onClick={() => {
              if (accessToken) {
                closeModal();
                return;
              }
              openModal("LOGIN", {});
            }}
            className="cursor-pointer font-medium text-link-1"
          >
            Back to Login
          </button>
        </p>
      ) : null}
    </div>
  );
}
