"use client";
import { useEffect, useState, useRef } from "react";
import { BeatLoader } from "react-spinners";
import { useSearchParams } from "next/navigation";
import { CardHeader } from "@/components/ui/card";
import { newVerification } from "@/actions/authActions";
import { FormError } from "@/components/form/FormError";
import { FormSuccess } from "@/components/form/FormSuccess";

const NewVerificationForm = () => {
  const [error, setError] = useState<string | undefined>();
  const [success, setSuccess] = useState<string | undefined>();
  const [loading, setLoading] = useState(true);

  // This ref survives across re-renders
  const verificationStarted = useRef(false);

  const searchParams = useSearchParams();
  const token = searchParams.get("token");

  useEffect(() => {
    // 1. Check if verification already started
    if (verificationStarted.current) return;
    verificationStarted.current = true;

    // 2. Check for token
    if (!token) {
      setLoading(false);
      setError("Missing token!");
      return;
    }

    // 3. Check if we already verified this token in this session
    const sessionKey = `verified_token_${token}`;
    const existingResult = sessionStorage.getItem(sessionKey);

    if (existingResult) {
      // We already verified this token
      setLoading(false);
      const result = JSON.parse(existingResult);
      if (result.success) {
        setSuccess(result.success);
      } else if (result.error) {
        setError(result.error);
      }
      return;
    }

    // 4. Perform verification
    const verifyToken = async () => {
      try {
        const result = await newVerification(token);

        // Store result in session storage
        sessionStorage.setItem(sessionKey, JSON.stringify(result));

        if (result.success) {
          setSuccess(result.success);
        } else if (result.error) {
          setError(result.error);
        }
      } catch (err) {
        console.error("Verification error:", err);
        setError("Something went wrong!");

        // Store error in session storage
        sessionStorage.setItem(
          sessionKey,
          JSON.stringify({ error: "Something went wrong!" }),
        );
      } finally {
        setLoading(false);
      }
    };

    verifyToken();
  }, [token]); // Only depend on token

  return (
    <div className="flex items-center justify-center">
      <div className="w-full">
        <CardHeader className="space-y-1 text-center">
          <h1 className="text-2xl font-bold tracking-tight">
            Email Verification
          </h1>
          <p className="text-sm text-muted-foreground">
            We&apos;re confirming your email address
          </p>
        </CardHeader>

        <div className="flex w-full flex-col items-center justify-center p-6">
          {loading && <BeatLoader color="#03045e" />}
          {!loading && success && <FormSuccess message={success} />}
          {!loading && error && <FormError message={error} />}
        </div>
      </div>
    </div>
  );
};

export default NewVerificationForm;
