"use client";

import { useState } from "react";
import Link from "next/link";
import { Mail, AlertCircle, MailCheck } from "lucide-react";
import { AuthCard } from "@/components/auth/AuthCard";
import { AuthTextField } from "@/components/auth/AuthTextField";
import { Button } from "@/components/ui/Button";
import { apiPost } from "@/lib/api/client";

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

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

    if (!email.trim()) {
      setError("Enter your email address.");
      return;
    }

    setLoading(true);
    try {
      await apiPost("/api/auth/forgot-password", { email: email.trim() });
    } catch (err) {
      // Always show success either way — avoids confirming/denying a
      // registered email (matches what the API itself does).
      // eslint-disable-next-line no-console
      console.error(err);
    } finally {
      setLoading(false);
      setSent(true);
    }
  }

  if (sent) {
    return (
      <AuthCard title="Check your email">
        <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">
            <MailCheck size={28} strokeWidth={1.8} className="text-gold-bright" />
          </div>
          <p className="text-sm leading-relaxed text-paper/70">
            If an admin account exists for{" "}
            <span className="font-semibold text-paper">{email}</span>, we've sent a password
            reset link.
          </p>
          <Link href="/login" className="w-full">
            <Button fullWidth>Back to Login</Button>
          </Link>
        </div>
      </AuthCard>
    );
  }

  return (
    <AuthCard title="Reset password" subtitle="We'll email you a link to set a new one">
      <form onSubmit={handleSubmit} className="flex flex-col gap-3.5">
        <AuthTextField
          label="Email"
          type="email"
          autoComplete="email"
          icon={Mail}
          placeholder="you@sharednet.pk"
          value={email}
          onChange={(e) => setEmail(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 ? "Sending…" : "Send Reset Link"}
        </Button>
      </form>
      <p className="mt-6 text-center text-sm text-paper/60">
        <Link href="/login" className="font-semibold text-gold-bright">
          Back to Login
        </Link>
      </p>
    </AuthCard>
  );
}
