"use client";

import Button from "@/components/ui/button/Button";
import { storeSignupSetupPasswordToken } from "@/lib/auth/signup-setup-token";
import { AlertCircle, ArrowLeft, LoaderCircle, MailCheck } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";

type VerificationState = "loading" | "success" | "error";

export default function VerifyEmailModule() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const challengeToken = useMemo(() => searchParams.get("token")?.trim() || "", [searchParams]);
  const [state, setState] = useState<VerificationState>("loading");
  const [message, setMessage] = useState("Verifying your email...");
  const [retryCount, setRetryCount] = useState(0);

  useEffect(() => {
    let isMounted = true;

    async function verifyEmail() {
      if (!challengeToken) {
        setState("error");
        setMessage("Verification link is invalid or expired.");
        return;
      }

      try {
        setState("loading");
        setMessage("Verifying your email...");

        const response = await fetch("/api/auth/email-verification/verify", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ challenge_token: challengeToken }),
        });
        const data = await response.json().catch(() => null);
        const setupPasswordToken = data?.result?.setup_password_token?.trim?.() || "";

        if (!response.ok || !data?.ok || !setupPasswordToken) {
          throw new Error("Verification link is invalid or expired.");
        }

        storeSignupSetupPasswordToken(setupPasswordToken);
        if (!isMounted) return;

        setState("success");
        setMessage("Email verified successfully. Redirecting to set your password...");
        router.replace("/signup/set-password");
      } catch {
        if (!isMounted) return;
        setState("error");
        setMessage("Verification link is invalid or expired.");
      }
    }

    verifyEmail();

    return () => {
      isMounted = false;
    };
  }, [challengeToken, router, retryCount]);

  const isError = state === "error";
  const isSuccess = state === "success";
  const iconContainerClass = isError
    ? "bg-error-50 text-error-600 dark:bg-error-500/10 dark:text-error-300"
    : "bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-300";

  return (
    <div className="flex flex-col justify-center flex-1 w-full max-w-md mx-auto">
      <div className="rounded-2xl border border-gray-200 bg-white p-6 shadow-theme-sm dark:border-gray-800 dark:bg-gray-900 sm:p-8">
        <div
          className={`mb-6 flex h-14 w-14 items-center justify-center rounded-full ${iconContainerClass}`}
        >
          {state === "loading" ? (
            <LoaderCircle className="h-7 w-7 animate-spin" />
          ) : isError ? (
            <AlertCircle className="h-7 w-7" />
          ) : (
            <MailCheck className="h-7 w-7" />
          )}
        </div>

        <div className="mb-6">
          <h1 className="text-2xl font-semibold text-gray-900 dark:text-white">
            {isError ? "Verification failed" : isSuccess ? "Email verified" : "Verifying email"}
          </h1>
          <p className="mt-3 text-sm leading-6 text-gray-500 dark:text-gray-400">{message}</p>
        </div>

        {isError && (
          <>
            <div className="rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-800 dark:bg-white/[0.03]">
              <p className="text-sm leading-6 text-gray-600 dark:text-gray-300">
                The verification link may have expired. Return to sign up and submit the form again
                to receive a fresh link.
              </p>
            </div>

            <div className="mt-6 space-y-3">
              <Button
                className="w-full"
                size="sm"
                variant="outline"
                onClick={() => {
                  setState("loading");
                  setMessage("Verifying your email...");
                  setRetryCount((count) => count + 1);
                }}
              >
                Try Again
              </Button>
              <Button asChild className="w-full" size="sm" variant="outline">
                <Link href="/signup">
                  <ArrowLeft className="h-4 w-4" />
                  Back to Sign Up
                </Link>
              </Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
