import { useMemo, useState, type FormEvent } from "react";
import { Link, useNavigate, useSearchParams } 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";
import { checkPasswordPolicy } from "../lib/passwordPolicy";

/**
 * 重設密碼：
 * - 從信內連結進來：?email=&token= 預填
 * - 從忘記密碼頁進來：可只帶 email，自行填驗證碼
 * - 手動進入：三欄都可填
 */
export function ResetPasswordPage() {
  const repos = useRepos();
  const { t } = useI18n();
  const formatApiError = useFormatApiError();
  const formatApiOk = useFormatApiOk();
  const navigate = useNavigate();
  const [params] = useSearchParams();

  const initialEmail = useMemo(() => (params.get("email") || "").trim(), [params]);
  const initialToken = useMemo(() => (params.get("token") || params.get("code") || "").trim(), [params]);

  const [email, setEmail] = useState(initialEmail);
  const [code, setCode] = useState(initialToken);
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [okMsg, setOkMsg] = useState("");

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError("");
    setOkMsg("");
    if (!email.trim()) {
      setError(t("reset.needEmail"));
      return;
    }
    if (!code.trim()) {
      setError(t("reset.needCode"));
      return;
    }
    if (password !== confirm) {
      setError(t("reset.mismatch"));
      return;
    }
    const policy = checkPasswordPolicy(password);
    if (!policy.ok) {
      setError(t(policy.errorKey || "password.policy.hint"));
      return;
    }
    setBusy(true);
    try {
      const res = await repos.auth.resetPassword(code.trim(), password, email.trim());
      setOkMsg(formatApiOk(res.message, "api.ok.passwordUpdated"));
      window.setTimeout(() => navigate("/login", { replace: true }), 1200);
    } catch (err) {
      setError(formatApiError(err, "reset.fail"));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hb-login">
      <Card title={t("reset.title")}>
        {okMsg ? (
          <div className="hb-stack">
            <p className="hb-banner-ok" role="status" style={{ margin: 0 }}>
              {okMsg}
            </p>
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
              {t("reset.redirecting")}
            </p>
            <Link to="/login">
              <Button type="button">{t("reset.loginNow")}</Button>
            </Link>
          </div>
        ) : (
          <form className="hb-stack" onSubmit={(e) => void onSubmit(e)}>
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>
              {t("reset.hint")}
            </p>
            <Input
              label={t("login.email")}
              name="email"
              type="email"
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <Input
              label={t("reset.code")}
              name="code"
              inputMode="numeric"
              autoComplete="one-time-code"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\s/g, "").slice(0, 12))}
              placeholder={t("reset.codePh")}
              required
            />
            <Input
              label={t("reset.newPassword")}
              name="password"
              type="password"
              autoComplete="new-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              placeholder={t("reset.passwordPh")}
            />
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-xs)" }}>
              {t("password.policy.hint")}
            </p>
            <Input
              label={t("reset.confirm")}
              name="confirm"
              type="password"
              autoComplete="new-password"
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              required
            />
            {error ? (
              <p className="hb-form-error" role="alert">
                {error}
              </p>
            ) : null}
            <Button type="submit" disabled={busy}>
              {busy ? t("reset.submitting") : t("reset.submit")}
            </Button>
            <Link to="/forgot-password" className="hb-login-back">
              {t("reset.forgotLink")}
            </Link>
            <Link to="/login" className="hb-login-back">
              {t("forgot.back")}
            </Link>
          </form>
        )}
      </Card>
    </div>
  );
}
