import { FormEvent, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { apiFetch, getToken, login, setSession } from "../api";

type LoginMeta = {
  show_default_hint: boolean;
  lan_login_available: boolean;
};

export default function LoginPage() {
  const nav = useNavigate();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [err, setErr] = useState("");
  const [loading, setLoading] = useState(false);
  const [showHint, setShowHint] = useState(false);
  const [lanTrying, setLanTrying] = useState(true);

  useEffect(() => {
    if (getToken()) {
      nav("/monitor", { replace: true });
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const meta = await apiFetch<LoginMeta>("/api/auth/login-meta");
        if (cancelled) return;
        setShowHint(!!meta.show_default_hint);
        if (meta.lan_login_available) {
          const res = await apiFetch<{ token: string; username: string }>(
            "/api/auth/lan-login",
            { method: "POST", body: "{}" },
          );
          if (cancelled) return;
          setSession(res.token, res.username);
          nav("/monitor", { replace: true });
          return;
        }
      } catch {
        /* 免登失败则走普通登录 */
      } finally {
        if (!cancelled) setLanTrying(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [nav]);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setErr("");
    setLoading(true);
    try {
      await login(username.trim(), password);
      nav("/monitor", { replace: true });
    } catch (ex) {
      setErr(ex instanceof Error ? ex.message : String(ex));
    } finally {
      setLoading(false);
    }
  }

  if (lanTrying) {
    return (
      <div className="login-wrap">
        <div className="login-box">
          <h1>比特骆驼中控</h1>
          <p className="meta">检测局域网免登录…</p>
        </div>
      </div>
    );
  }

  return (
    <div className="login-wrap">
      <form
        className="login-box"
        onSubmit={onSubmit}
        autoComplete="off"
        data-lpignore="true"
      >
        <h1>比特骆驼中控</h1>
        <p className="meta">
          本地运维面板
          {showHint ? " · 默认 admin / admin123" : ""}
        </p>
        {err ? <div className="err">{err}</div> : null}
        <label>
          用户名
          <input
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoComplete="off"
            autoCorrect="off"
            autoCapitalize="off"
            spellCheck={false}
            name="control-login-user"
            required
          />
        </label>
        <label>
          密码
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="new-password"
            name="control-login-pass"
            required
          />
        </label>
        <button className="btn" type="submit" disabled={loading}>
          {loading ? "登录中…" : "登录"}
        </button>
      </form>
    </div>
  );
}
