"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Lock, AlertCircle, ShieldAlert, KeyRound } from "lucide-react";
import { AuthCard } from "@/components/auth/AuthCard";
import { AuthTextField } from "@/components/auth/AuthTextField";
import { Button } from "@/components/ui/Button";
import { apiPost, ApiError } from "@/lib/api/client";

function ResetPasswordContent() {
  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("Password must be at least 8 characters.");
      return;
    }
    if (password !== confirmPassword) {
      setError("Passwords don't match.");
      return;
    }

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

  // No token at all in the URL — same "link expired" screen an
  // actually-expired/already-used token gets from the API below.
  if (!token) {
    return (
      <AuthCard title="Link expired">
        <div className="flex flex-col items-center gap-4 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-danger/15">
            <ShieldAlert size={28} strokeWidth={1.8} className="text-danger" />
          </div>
          <p className="text-sm leading-relaxed text-paper/70">
            This password reset link is invalid or has expired.
          </p>
          <Link href="/forgot-password" className="w-full">
            <Button fullWidth>Request New Link</Button>
          </Link>
        </div>
      </AuthCard>
    );
  }

  if (done) {
    return (
      <AuthCard title="Password updated">
        <div className="flex flex-col items-center gap-4 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-gold/15">
            <KeyRound size={28} strokeWidth={1.8} className="text-gold-bright" />
          </div>
          <p className="text-sm leading-relaxed text-paper/70">
            Your password has been changed. Log in with your new password to continue.
          </p>
          <Link href="/login" className="w-full">
            <Button fullWidth>Go to Log In</Button>
          </Link>
        </div>
      </AuthCard>
    );
  }

  return (
    <AuthCard title="Set a new password">
      <form onSubmit={handleSubmit} className="flex flex-col gap-3.5">
        <AuthTextField
          label="New Password"
          type="password"
          autoComplete="new-password"
          icon={Lock}
          placeholder="At least 8 characters"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <AuthTextField
          label="Confirm New Password"
          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-2.5 text-xs text-danger">
            <AlertCircle size={14} className="mt-0.5 shrink-0" />
            {error}
          </div>
        )}
        <Button type="submit" fullWidth disabled={loading} className="mt-1">
          {loading ? "Saving…" : "Save New Password"}
        </Button>
      </form>
    </AuthCard>
  );
}

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