"use client";

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

function ResetPasswordContent() {
  const { t } = useTranslation();
  const searchParams = useSearchParams();
  const token = searchParams.get("token");

  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (password.length < 8) {
      setError(t("resetPassword.passwordTooShort"));
      return;
    }
    if (password !== confirmPassword) {
      setError(t("resetPassword.passwordMismatch"));
      return;
    }

    setLoading(true);
    try {
      await apiPost("/api/auth/reset-password", { token, newPassword: password });
      setDone(true);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : t("common.genericError"));
    } finally {
      setLoading(false);
    }
  }

  // No token at all in the URL — same "link expired" screen as an
  // actually-expired/already-used token gets from the API below.
  if (!token) {
    return (
      <AuthShell title={t("resetPassword.linkExpiredTitle")} backHref="/forgot-password">
        <div className="flex flex-col items-center gap-5 text-center">
          <div className="flex h-20 w-20 items-center justify-center rounded-full bg-danger/15">
            <ShieldAlert size={36} strokeWidth={1.8} className="text-danger" />
          </div>
          <p className="text-sm leading-relaxed text-paper/70">
            {t("resetPassword.linkExpiredDesc")}
          </p>
          <Link href="/forgot-password">
            <Button size="lg">{t("resetPassword.requestNewLink")}</Button>
          </Link>
        </div>
      </AuthShell>
    );
  }

  if (done) {
    return (
      <AuthShell title={t("resetPassword.successTitle")}>
        <div className="flex flex-col items-center gap-5 text-center">
          <motion.div
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ type: "spring", stiffness: 260, damping: 18 }}
            className="flex h-20 w-20 items-center justify-center rounded-full bg-gold/15"
          >
            <KeyRound size={36} strokeWidth={1.8} className="text-gold-bright" />
          </motion.div>
          <p className="text-sm leading-relaxed text-paper/70">{t("resetPassword.successDesc")}</p>
          <Link href="/login">
            <Button size="lg">{t("resetPassword.goToLogin")}</Button>
          </Link>
        </div>
      </AuthShell>
    );
  }

  return (
    <AuthShell
      title={t("resetPassword.setNewPasswordTitle")}
      subtitle={t("resetPassword.setNewPasswordSubtitle")}
    >
      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <TextField
          label={t("resetPassword.newPassword")}
          type="password"
          autoComplete="new-password"
          icon={Lock}
          placeholder="At least 8 characters"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <TextField
          label={t("resetPassword.confirmNewPassword")}
          type="password"
          autoComplete="new-password"
          icon={Lock}
          placeholder="••••••••"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
        />

        {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>
        )}

        <Button type="submit" size="lg" fullWidth disabled={loading}>
          {loading ? t("resetPassword.saving") : t("resetPassword.saveNewPassword")}
        </Button>
      </form>
    </AuthShell>
  );
}

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