import { useState, type FormEvent } from "react";
import { Link } from "react-router-dom";
import { Button, Card, Input } from "../components/ui";
import { useRepos } from "../data/DataContext";
import { useI18n } from "../i18n/I18nContext";
import { useFormatApiError, useFormatApiOk } from "../lib/apiErrors";

export function ForgotPasswordPage() {
  const repos = useRepos();
  const { t } = useI18n();
  const formatApiError = useFormatApiError();
  const formatApiOk = useFormatApiOk();
  const [email, setEmail] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState<{ message: string; email: string } | null>(null);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError("");
    setDone(null);
    try {
      const trimmed = email.trim();
      const res = await repos.auth.requestPasswordReset(trimmed);
      setDone({
        message: formatApiOk(res.message, "api.ok.resetSent"),
        email: trimmed,
      });
    } catch (err) {
      setError(formatApiError(err, "forgot.fail"));
    } finally {
      setBusy(false);
    }
  }

  const resetPath = done
    ? `/reset-password?email=${encodeURIComponent(done.email)}`
    : "/reset-password";

  return (
    <div className="hb-login">
      <Card title={t("forgot.title")}>
        {done ? (
          <div className="hb-stack">
            <p className="hb-banner-ok" role="status" style={{ margin: 0 }}>
              {done.message}
            </p>
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
              {t("forgot.checkInbox")}
            </p>
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
              {t("forgot.nextStep")}
            </p>
            <Link to={resetPath} className="hb-btn hb-btn--primary">{t("forgot.openReset")}</Link>
            <div className="hb-wizard-actions">
              <Link to="/login" className="hb-btn hb-btn--ghost">{t("forgot.back")}</Link>
              <Button
                type="button"
                variant="ghost"
                onClick={() => {
                  setDone(null);
                  setError("");
                }}
              >
                {t("forgot.retry")}
              </Button>
            </div>
          </div>
        ) : (
          <form className="hb-stack" onSubmit={(e) => void onSubmit(e)}>
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
              {t("forgot.hint")}
            </p>
            <Input
              label={t("login.email")}
              name="email"
              type="email"
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            {error ? (
              <p className="hb-form-error" role="alert">
                {error}
              </p>
            ) : null}
            <Button type="submit" disabled={busy}>
              {busy ? t("forgot.submitting") : t("forgot.submit")}
            </Button>
            <Link to="/login" className="hb-login-back">
              {t("forgot.back")}
            </Link>
          </form>
        )}
      </Card>
    </div>
  );
}
