"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Mail, Lock, AlertCircle } from "lucide-react";
import { AuthShell } from "@/components/auth/AuthShell";
import { TextField } from "@/components/ui/TextField";
import { Button } from "@/components/ui/Button";
import { useAuth } from "@/lib/auth/auth-provider";
import { apiPost, ApiError } from "@/lib/api/client";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

function LoginContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get("redirect") || "/home";
  const { t } = useTranslation();
  const { refreshProfile } = useAuth();

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [needsVerification, setNeedsVerification] = useState(false);
  const [resendState, setResendState] = useState<"idle" | "sending" | "sent">("idle");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setNeedsVerification(false);
    setResendState("idle");

    if (!email.trim() || !password) {
      setError(t("login.fillFields"));
      return;
    }

    setLoading(true);
    try {
      await apiPost("/api/auth/login", { email: email.trim(), password });
      await refreshProfile();
      router.push(redirect);
      router.refresh();
    } catch (err) {
      if (!(err instanceof ApiError)) {
        setError(t("common.genericError"));
        return;
      }
      if (err.code === "EMAIL_NOT_VERIFIED") {
        setNeedsVerification(true);
        setError(err.message);
        return;
      }
      // Matches the original behavior: the generic "wrong email or
      // password" case is translated; every other server message
      // (rate limited, blocked account, ...) is shown as-is.
      setError(err.status === 401 ? t("login.wrongCredentials") : err.message);
    } finally {
      setLoading(false);
    }
  }

  async function handleResend() {
    setResendState("sending");
    try {
      await apiPost("/api/auth/resend-verification", { email: email.trim() });
    } finally {
      // Always shows success — the API itself never reveals whether the
      // email exists, so there's nothing more specific to branch on here.
      setResendState("sent");
    }
  }

  return (
    <AuthShell title={t("login.title")} subtitle={t("login.subtitle")} backHref="/welcome">
      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <TextField
          label={t("login.email")}
          type="email"
          autoComplete="email"
          icon={Mail}
          placeholder="you@example.com"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <div>
          <TextField
            label={t("login.password")}
            type="password"
            autoComplete="current-password"
            icon={Lock}
            placeholder="••••••••"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <Link
            href="/forgot-password"
            className="mt-2 inline-block text-xs font-semibold text-gold-bright"
          >
            {t("login.forgotPassword")}
          </Link>
        </div>

        {error && (
          <div className="flex items-start gap-2 rounded-xl bg-danger/10 px-3.5 py-3 text-sm text-danger">
            <AlertCircle size={16} className="mt-0.5 shrink-0" />
            {error}
          </div>
        )}

        {needsVerification && (
          <button
            type="button"
            onClick={handleResend}
            disabled={resendState === "sending"}
            className="text-left text-sm font-semibold text-gold-bright disabled:opacity-60"
          >
            {resendState === "sent"
              ? t("login.verificationResent")
              : resendState === "sending"
                ? t("login.resendingVerification")
                : t("login.resendVerification")}
          </button>
        )}

        <Button type="submit" size="lg" fullWidth disabled={loading}>
          {loading ? t("login.loggingIn") : t("login.logIn")}
        </Button>
      </form>

      <p className="mt-6 text-center text-sm text-paper/60">
        {t("login.noAccount")}{" "}
        <Link href="/signup" className="font-semibold text-gold-bright">
          {t("login.signUp")}
        </Link>
      </p>
    </AuthShell>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginContent />
    </Suspense>
  );
}
