import { useEffect, useState } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { verifyEmail } from "@/lib/api";
import { Button } from "@/components/ui/button";

export function VerifyEmail() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [isVerifying, setIsVerifying] = useState(true);

  useEffect(() => {
    const token = searchParams.get("token");
    if (token) {
      (async () => {
        try {
          await verifyEmail(token);
          toast.success("Email verified successfully! Please log in.");
          // Redirect to login after a short delay
          setTimeout(() => {
            navigate("/login");
          }, 3000);
        } catch (error: any) {
          toast.error(error.message || "Email verification failed");
        } finally {
          setIsVerifying(false);
        }
      })();
    } else {
      toast.error("Verification token not found");
      setIsVerifying(false);
    }
  }, [navigate, searchParams]);

  return (
    <div className="flex flex-col items-center justify-center py-10">
      {isVerifying ? (
        <p>Verifying your email...</p>
      ) : (
        <Button onClick={() => navigate("/login")}>
          Go to Login
        </Button>
      )}
    </div>
  );
}
