import { useEffect, useState, type FormEvent } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { useAuth } from "../auth/AuthContext";
import { Button, Card, Input } from "../components/ui";
import { useRepos } from "../data/DataContext";
import { useI18n } from "../i18n/I18nContext";
import { useFormatApiError, useFormatApiOk } from "../lib/apiErrors";
import { memberRoleSummary } from "../lib/memberRole";

/** 信箱驗證：未驗證不可進 App；完成後固定進今日。 */
export function VerifyEmailPage() {
  const repos = useRepos();
  const { member, loading, logout, reload } = useAuth();
  const { t } = useI18n();
  const formatApiError = useFormatApiError();
  const formatApiOk = useFormatApiOk();
  const navigate = useNavigate();

  const [code, setCode] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState("");

  useEffect(() => {
    if (!member || member.email_verified) return;
    void sendCode(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [member?.email, member?.email_verified]);

  if (loading) {
    return (
      <div className="hb-login">
        <p className="text-muted">{t("common.loading")}</p>
      </div>
    );
  }

  if (!member) {
    return <Navigate to="/login" replace />;
  }

  if (member.email_verified) {
    return <Navigate to="/app/today" replace />;
  }

  const role = memberRoleSummary(member, t);

  async function sendCode(manual: boolean) {
    setBusy("send");
    setError("");
    if (manual) setMessage("");
    try {
      const res = await repos.auth.sendEmailVerificationCode();
      setMessage(formatApiOk(res.message, "api.ok.verifySent"));
    } catch (e) {
      setError(formatApiError(e, "verify.sendFail"));
    } finally {
      setBusy("");
    }
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setBusy("verify");
    setError("");
    setMessage("");
    try {
      await repos.auth.verifyEmail(code);
      await reload();
      navigate("/app/today", { replace: true });
    } catch (err) {
      setError(formatApiError(err, "verify.fail"));
    } finally {
      setBusy("");
    }
  }

  return (
    <div className="hb-login">
      <Card title={t("verify.title")}>
        <div className="hb-stack">
          <div className="hb-verify-status">
            <span className="hb-verify-status__badge is-pending">{t("verify.pending")}</span>
            <p style={{ margin: 0, fontSize: "var(--hb-text-sm)" }}>{t("verify.body")}</p>
            <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-xs)" }}>
              {t("verify.currentAccount", { email: member.email })}
              {" · "}
              {role.primaryLabel}
            </p>
          </div>

          {message ? (
            <p className="hb-banner-ok" role="status" style={{ margin: 0 }}>
              {message}
            </p>
          ) : null}
          {error ? (
            <p className="hb-form-error" role="alert">
              {error}
            </p>
          ) : null}

          <form className="hb-stack" onSubmit={(e) => void onSubmit(e)}>
            <Input
              label={t("verify.code")}
              name="code"
              inputMode="numeric"
              autoComplete="one-time-code"
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
              placeholder={t("verify.codePh")}
              required
            />
            <Button type="submit" disabled={busy === "verify" || code.length !== 6}>
              {busy === "verify" ? t("verify.submitting") : t("verify.submit")}
            </Button>
          </form>

          <div className="hb-wizard-actions" style={{ justifyContent: "space-between" }}>
            <Button
              type="button"
              variant="ghost"
              disabled={busy === "send"}
              onClick={() => void sendCode(true)}
            >
              {busy === "send" ? t("verify.sending") : t("verify.resend")}
            </Button>
            <Button
              type="button"
              variant="ghost"
              onClick={() => {
                void logout().then(() => navigate("/login"));
              }}
            >
              {t("verify.logout")}
            </Button>
          </div>

          <p className="text-muted" style={{ margin: 0, fontSize: "var(--hb-text-xs)", textAlign: "center" }}>
            {t("verify.after")}
          </p>
        </div>
      </Card>
    </div>
  );
}
