import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { z } from "zod";
import { AuthLayout } from "@/components/auth-layout";
import { Button } from "@/components/ui/button";
import { MailCheck, CheckCircle2, XCircle } from "lucide-react";
import { toast } from "sonner";
import { resendVerificationFn, verifyEmailFn } from "@/lib/auth/auth.functions";

const searchSchema = z.object({
  token: z.string().optional(),
  email: z.string().optional(),
});

export const Route = createFileRoute("/verify-email")({
  validateSearch: searchSchema,
  head: () => ({ meta: [{ title: "Verify email — VotersAlert" }] }),
  component: Page,
});

function Page() {
  const navigate = useNavigate();
  const { token, email } = Route.useSearch();
  const [status, setStatus] = useState<"idle" | "verifying" | "success" | "error">(
    token ? "verifying" : "idle",
  );
  const [message, setMessage] = useState<string | null>(null);
  const [resending, setResending] = useState(false);

  useEffect(() => {
    if (!token) return;
    let cancelled = false;
    (async () => {
      try {
        await verifyEmailFn({ data: { token } });
        if (cancelled) return;
        setStatus("success");
        toast.success("Email verified. You can sign in now.");
        setTimeout(() => navigate({ to: "/login" }), 1500);
      } catch (err) {
        if (cancelled) return;
        setStatus("error");
        setMessage(err instanceof Error ? err.message : "Verification failed.");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [token, navigate]);

  const onResend = async () => {
    if (!email) {
      toast.error("Provide your email on the registration form to resend.");
      return;
    }
    setResending(true);
    try {
      await resendVerificationFn({ data: { email } });
      toast.success("If the account exists, a new link has been sent.");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not resend.");
    } finally {
      setResending(false);
    }
  };

  return (
    <AuthLayout
      title="Verify your email"
      subtitle={
        email
          ? `We sent a verification link to ${email}`
          : "Check your inbox for a verification link."
      }
      footer={
        <Link to="/login" className="text-primary font-medium hover:underline">
          Back to sign in
        </Link>
      }
    >
      <div className="rounded-xl border bg-gradient-to-br from-primary/5 to-accent/5 p-6 text-center">
        <div className="mx-auto h-12 w-12 rounded-full bg-primary/10 grid place-items-center">
          {status === "success" ? (
            <CheckCircle2 className="h-6 w-6 text-success" />
          ) : status === "error" ? (
            <XCircle className="h-6 w-6 text-destructive" />
          ) : (
            <MailCheck className="h-6 w-6 text-primary" />
          )}
        </div>
        <p className="mt-3 text-sm text-muted-foreground">
          {status === "verifying" && "Verifying your email…"}
          {status === "success" && "Email verified. Redirecting to sign in…"}
          {status === "error" && (message ?? "We couldn't verify that link.")}
          {status === "idle" &&
            "Click the link in the email to activate your workspace. Didn't get it? Check spam or resend below."}
        </p>
        {(status === "idle" || status === "error") && (
          <Button className="mt-4 w-full" onClick={onResend} disabled={resending || !email}>
            {resending ? "Sending…" : "Resend verification email"}
          </Button>
        )}
      </div>
    </AuthLayout>
  );
}
