"use client";

import { useEffect, useState, useTransition } from "react";
import Link from "next/link";
import { CheckCircle2, XCircle, Loader2, MailCheck } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { verifyEmailAction, resendVerificationAction } from "@/actions/verification-actions";
import { useLanguage } from "@/lib/i18n/context";
import { safeRelativePath } from "@/emails/security";

type Status = "pending" | "verifying" | "success" | "error";

export function VerifyEmailStatus({
  token,
  email,
  callbackUrl,
}: {
  token?: string;
  email?: string;
  callbackUrl?: string;
}) {
  const safeCallbackUrl = safeRelativePath(callbackUrl);
  const loginHref = safeCallbackUrl
    ? `/login?callbackUrl=${encodeURIComponent(safeCallbackUrl)}`
    : "/login";
  const { t, locale } = useLanguage();
  const v = t.auth.verifyStatus;
  const [status, setStatus] = useState<Status>(token ? "verifying" : "pending");
  const [error, setError] = useState<string | null>(null);
  const [isResending, startResend] = useTransition();

  useEffect(() => {
    if (!token) return;

    let cancelled = false;
    verifyEmailAction(token, locale).then((result) => {
      if (cancelled) return;
      if (result.success) {
        setStatus("success");
      } else {
        setStatus("error");
        setError(result.error);
      }
    });

    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- only re-run on token change; a locale switch mid-verification shouldn't re-trigger the network call
  }, [token]);

  function handleResend() {
    if (!email) return;
    startResend(async () => {
      const result = await resendVerificationAction(email, locale);
      toast.success(result.success ? (result.message ?? t.errors.resendVerificationSuccess) : result.error);
    });
  }

  if (status === "verifying") {
    return (
      <div className="flex flex-col items-center gap-3 py-2 text-center">
        <Loader2 className="size-8 animate-spin text-primary" />
        <p className="text-sm text-muted-foreground">{v.verifying}</p>
      </div>
    );
  }

  if (status === "success") {
    return (
      <div className="flex flex-col items-center gap-4 py-2 text-center">
        <span className="flex size-12 items-center justify-center rounded-full bg-success/15 text-success">
          <CheckCircle2 className="size-6" />
        </span>
        <p className="text-sm text-muted-foreground">{v.success}</p>
        <Button asChild size="lg" className="w-full">
          <Link href={loginHref}>{v.continueToLogIn}</Link>
        </Button>
      </div>
    );
  }

  if (status === "error") {
    return (
      <div className="flex flex-col items-center gap-4 py-2 text-center">
        <span className="flex size-12 items-center justify-center rounded-full bg-destructive/15 text-destructive">
          <XCircle className="size-6" />
        </span>
        <p className="text-sm text-muted-foreground">{error}</p>
        {email ? (
          <Button
            variant="outline"
            size="lg"
            className="w-full"
            onClick={handleResend}
            disabled={isResending}
          >
            {isResending ? <Loader2 className="size-4 animate-spin" /> : null}
            {v.sendNewLink}
          </Button>
        ) : (
          <Button asChild variant="outline" size="lg" className="w-full">
            <Link href="/login">{v.backToLogIn}</Link>
          </Button>
        )}
      </div>
    );
  }

  // pending — just registered, waiting on the user to click the emailed link
  const [beforeEmail, afterEmail] = v.pendingWithEmail.split("{email}");

  return (
    <div className="flex flex-col items-center gap-4 py-2 text-center">
      <span className="flex size-12 items-center justify-center rounded-full bg-primary/15 text-primary">
        <MailCheck className="size-6" />
      </span>
      <p className="text-sm text-muted-foreground">
        {email ? (
          <>
            {beforeEmail}
            <span className="text-foreground">{email}</span>
            {afterEmail}
          </>
        ) : (
          v.pendingNoEmail
        )}
      </p>
      {email ? (
        <Button
          variant="outline"
          size="lg"
          className="w-full"
          onClick={handleResend}
          disabled={isResending}
        >
          {isResending ? <Loader2 className="size-4 animate-spin" /> : null}
          {v.resendEmail}
        </Button>
      ) : null}
    </div>
  );
}
