import { useState, type FormEvent } from "react";
import { Link, Navigate, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../auth/AuthContext";
import { BrandMark, Button, Card, Input } from "../components/ui";
import { useI18n } from "../i18n/I18nContext";
import { useFormatApiError } from "../lib/apiErrors";

export function LoginPage() {
  const { member, login, loading } = useAuth();
  const { t } = useI18n();
  const formatApiError = useFormatApiError();
  const navigate = useNavigate();
  const location = useLocation();
  const from = (location.state as { from?: string } | null)?.from || "/app/today";

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  if (!loading && member) {
    return <Navigate to={from} replace />;
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError("");
    try {
      await login(email, password);
      navigate(from, { replace: true });
    } catch (err) {
      setError(formatApiError(err, "common.error"));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hb-login">
      <Card title={t("login.title")}>
        <div className="hb-login-brand">
          <BrandMark size={40} title={t("login.brandTitle")} />
          <div className="hb-login-brand__text">
            <strong>{t("app.name")}</strong>
            <span className="text-muted display-en">{t("app.nameEn")}</span>
          </div>
        </div>
        <form className="hb-stack" onSubmit={(e) => void onSubmit(e)}>
          <Input
            label={t("login.email")}
            name="email"
            type="email"
            autoComplete="username"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
          <div className="hb-login-password-field">
            <Input
              label={t("login.password")}
              name="password"
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              revealPassword
              revealShowLabel={t("login.showPassword")}
              revealHideLabel={t("login.hidePassword")}
            />
            <Link to="/forgot-password" className="hb-login-forgot">
              {t("login.forgot")}
            </Link>
          </div>
          {error ? (
            <p className="hb-form-error" role="alert">
              {error}
            </p>
          ) : null}
          <Button type="submit" disabled={busy || loading}>
            {busy ? t("login.submitting") : t("login.submit")}
          </Button>
          <div className="hb-login-public-links">
            <Link to="/" className="hb-login-back">
              {t("privacy.backHome")}
            </Link>
            <Link to="/privacy" className="hb-login-back">
              {t("home.privacyLink")}
            </Link>
            <Link to="/terms" className="hb-login-back">
              {t("home.termsLink")}
            </Link>
            <Link to="/data-deletion" className="hb-login-back">
              {t("home.dataDeletionLink")}
            </Link>
          </div>
        </form>
      </Card>
    </div>
  );
}
