"use client";

import { useState } from "react";
import { useI18n } from "../../components/I18nProvider";

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

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSent(false);
    setLoading(true);
    try {
      const res = await fetch("/api/auth/forgot", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error || t("forgotError"));
      } else {
        setSent(true);
      }
    } catch (err) {
      setError(t("forgotError"));
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="panel" style={{ maxWidth: 480, margin: "40px auto" }}>
      <h1>{t("forgotTitle")}</h1>
      <p style={{ color: "#cbd5e1", marginTop: 6 }}>{t("forgotLead")}</p>
      <form
        onSubmit={onSubmit}
        style={{ display: "grid", gap: 12, marginTop: 14 }}
      >
        <label>
          {t("emailLabel")}
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </label>
        <button className="button" type="submit" disabled={loading}>
          {loading ? t("submittingListing") : t("forgotSubmit")}
        </button>
      </form>
      {sent ? (
        <p style={{ marginTop: 12, color: "green" }}>{t("forgotSuccess")}</p>
      ) : null}
      {error ? <p style={{ marginTop: 12, color: "red" }}>{error}</p> : null}
    </main>
  );
}
