"use client";
import { useState } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { apiFetch } from "@/lib/api";
import { KeyRound } from "lucide-react";

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

    const submit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!email) return;
        try {
            setLoading(true);
            setStatus(null);
            const res: any = await apiFetch("/api/users/forgot", { method: "POST", body: { email } });
            setStatus(res?.message || "If that email exists, a password reset link has been sent.");
        } catch (err: any) {
            try {
                const parsed = JSON.parse(err?.message || "");
                setStatus(parsed?.message || "Something went wrong");
            } catch {
                setStatus(err?.message || "Something went wrong");
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen flex flex-col">
            <Navbar />
            <main className="flex-1 flex items-center justify-center p-6 bg-gradient-to-br from-brand-50 via-white to-brand-50">
                <div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="w-11 h-11 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
                            <KeyRound className="w-5 h-5 text-brand-600" />
                        </div>
                        <h1 className="text-xl font-semibold text-gray-900">Forgot your password?</h1>
                    </div>
                    <p className="text-gray-600 text-sm mb-6">Enter your account email and we'll send you a link to reset your password.</p>
                    <form onSubmit={submit} className="space-y-4">
                        <div>
                            <label className="block text-sm font-medium mb-1">Email</label>
                            <input type="email" value={email} onChange={e => setEmail(e.target.value)} required className="w-full border rounded px-3 py-2" />
                        </div>
                        <button disabled={loading || !email} className="px-4 py-2 rounded bg-brand-600 hover:bg-brand-700 text-white disabled:opacity-60">
                            {loading ? "Sending..." : "Send reset link"}
                        </button>
                    </form>
                    {status && <p className="text-sm text-gray-700 mt-4">{status}</p>}
                </div>
            </main>
            <Footer />
        </div>
    );
}
