"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { FiCheckCircle, FiInfo, FiMail, FiXCircle } from "react-icons/fi";

import Button from "../../ui/Button";
import { useModal } from "../../../lib/modal-system/ModalContext";
import { MODAL_TYPES } from "../../../lib/modal-system/ModalRegistery";
import useVerifyEmail from "../../../hooks/features/auth/verify-email/useVerifyEmail";
import { AxiosError } from "axios";
import { ErrorApiResponse } from "../../../types/api-response";
import { useAppDispatch, useAppSelector } from "../../../hooks/useAppRedux";
import { updateUser } from "../../../store/slices/user";
import useResendEmail from "../../../hooks/features/auth/resend-email/useResendEmail";

const REDIRECT_DELAY = 5;
const ALREADY_VERIFIED_MESSAGE = "Email already verified";

export default function VerifyEmailModal({ token }: { token?: string }) {
  const router = useRouter();
  const { openModal, closeModal } = useModal();
  const dispatch = useAppDispatch();
  const accessToken = useAppSelector((state) => state.user.token);
  const user = useAppSelector((state) => state.user.user);

  const { handleResendEmail, loading: resendLoading } = useResendEmail();

  const { data, loading, isError, error } = useVerifyEmail(token);

  const serverMessage = (error as AxiosError<ErrorApiResponse<unknown>>)
    ?.response?.data?.message;

  const isAlreadyVerified = serverMessage === ALREADY_VERIFIED_MESSAGE;

  const isLoading = loading;
  const isInfo = isError && isAlreadyVerified;
  const isSuccess = !isLoading && !isError && !!data;
  const isFailed = isError && !isAlreadyVerified;

  const message = isSuccess
    ? "Your email has been verified successfully!"
    : isInfo
      ? accessToken
        ? "Your email is already verified."
        : "Your email is already verified. You can log in."
      : (serverMessage ?? "This verification link is invalid or has expired.");

  const [countdown, setCountdown] = useState(REDIRECT_DELAY);

  useEffect(() => {
    if (!isSuccess && !isInfo) return;

    if (isSuccess) {
      dispatch(updateUser({ isVerified: true }));
    }
    if (countdown <= 0) {
      // router.push(`/`);
      const urlParams = new URLSearchParams(window.location.search);
      urlParams.delete("token");
      urlParams.delete("modal");
      urlParams.delete("status");
      const newSearch = urlParams.toString();

      window.history.replaceState(
        {},
        "",
        newSearch ? `?${newSearch}` : window.location.pathname,
      );

      closeModal();
      return;
    }
    const timer = setTimeout(() => setCountdown((c) => c - 1), 1000);
    return () => clearTimeout(timer);
  }, [isSuccess, isInfo, countdown, router]);

  return (
    <div className="text-center">
      {/* Icon */}
      <div
        className={`mx-auto flex h-16 w-16 items-center justify-center rounded-full
          ${isLoading ? "animate-spin border-4 border-[#E5D8FF] border-t-link-1" : ""}
          ${isSuccess ? "bg-success-light" : ""}
          ${isInfo ? "bg-blue-100" : ""}
          ${isFailed ? "bg-danger-light" : ""}
        `}
      >
        {isSuccess && <FiCheckCircle size={32} className="text-green-600" />}
        {isInfo && <FiInfo size={32} className="text-blue-600" />}
        {isFailed && <FiXCircle size={32} className="text-danger" />}
      </div>

      {/* Heading */}
      {!isLoading && (
        <h2 className="mt-5 text-2xl font-semibold text-heading">
          {isSuccess && "Email Verified"}
          {isInfo && "Already Verified"}
          {isFailed && "Verification Failed"}
        </h2>
      )}

      {/* Message */}
      <p className="mt-3 text-text">
        {isLoading ? "Verifying your email, please wait…" : message}
      </p>

      {/* Countdown */}
      {(isSuccess || isInfo) && (
        <p className="mt-5 text-sm text-text">
          {accessToken ? "Closing in" : "Redirecting to login in"}{" "}
          <span className="font-semibold text-link-1">{countdown}</span>{" "}
          seconds…
        </p>
      )}

      {/* Actions */}
      {!isLoading && (
        <div className="mt-6 flex flex-col items-center gap-3">
          {isFailed ? (
            <>
              <Button
                type="button"
                onClick={async () => {
                  // this is when user comes from email link
                  if (user) {
                    await handleResendEmail({ email: user?.email });
                    return;
                  }

                  openModal("ENTER_MAIL_FOR_RESEND_LINK", {});
                }}
              >
                Resend Verification Email
              </Button>
              {!accessToken && (
                <button
                  type="button"
                  onClick={() => {
                    const urlParams = new URLSearchParams(
                      window.location.search,
                    );
                    urlParams.delete("token");
                    urlParams.delete("modal");
                    urlParams.delete("status");
                    const newSearch = urlParams.toString();

                    window.history.replaceState(
                      {},
                      "",
                      newSearch ? `?${newSearch}` : window.location.pathname,
                    );

                    openModal(MODAL_TYPES.LOGIN, {});
                  }}
                  className="text-sm font-medium text-link-1 cursor-pointer"
                >
                  Back to Login
                </button>
              )}
            </>
          ) : (
            <Button
              type="button"
              onClick={() => {
                const urlParams = new URLSearchParams(window.location.search);
                urlParams.delete("token");
                urlParams.delete("modal");
                urlParams.delete("status");
                const newSearch = urlParams.toString();

                window.history.replaceState(
                  {},
                  "",
                  newSearch ? `?${newSearch}` : window.location.pathname,
                );

                if (accessToken) {
                  closeModal();
                } else {
                  openModal(MODAL_TYPES.LOGIN, {});
                }
              }}
            >
              {accessToken ? "Continue" : "Login Now"}
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
