"use client";

import { useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { Loader2 } from "lucide-react";
import { Link } from "@/i18n/navigation";
import AuthLayout from "@/components/auth/AuthLayout";
import Input from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import { readApiJson, toastPromise } from "@/lib/toast";

export default function ResendVerificationForm() {
  const t = useTranslations("auth");
  const locale = useLocale();
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);

    try {
      await toastPromise(
        readApiJson(
          await fetch("/api/auth/resend-verification", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ email: email.trim().toLowerCase(), locale }),
          }),
          t("networkError")
        ),
        {
          loading: t("sendingVerification"),
          success: t("verificationEmailSent"),
          error: (err) =>
            err instanceof Error ? err.message : t("networkError"),
        }
      );
      setSent(true);
    } catch {
      // surfaced via toast
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthLayout title={t("verifyEmailTitle")} subtitle={sent ? t("verificationEmailSent") : t("verifyEmailSubtitle")}>
      {sent ? (
        <div className="space-y-4 text-center">
          <p className="text-sm text-[var(--text-muted)]">{t("verificationEmailHint")}</p>
          <Link
            href="/login"
            className="inline-flex cursor-pointer text-sm font-medium text-[var(--accent)] transition-colors hover:text-[var(--accent-hover)]"
          >
            {t("backToSignIn")}
          </Link>
        </div>
      ) : (
        <>
          <form onSubmit={handleSubmit} className="space-y-5" noValidate>
            <Input
              label={t("email")}
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t("emailPlaceholder")}
              autoComplete="email"
              required
              disabled={loading}
            />

            <Button type="submit" disabled={loading} className="w-full" size="lg">
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  {t("sendingVerification")}
                </>
              ) : (
                t("resendVerification")
              )}
            </Button>
          </form>

          <p className="mt-6 text-center text-sm text-[var(--text-muted)]">
            <Link
              href="/login"
              className="cursor-pointer font-medium text-[var(--accent)] transition-colors hover:text-[var(--accent-hover)]"
            >
              {t("backToSignIn")}
            </Link>
          </p>
        </>
      )}
    </AuthLayout>
  );
}
