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

type ExchangeRes = {
  token: string;
  username: string;
  expires_in: number;
};

export default function LoginPage() {
  const nav = useNavigate();
  const [params] = useSearchParams();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [err, setErr] = useState("");
  const [loading, setLoading] = useState(false);
  const [ticketBusy, setTicketBusy] = useState(false);
  const [machineName, setMachineName] = useState("");

  useEffect(() => {
    let cancelled = false;
    void fetchMachineName().then((name) => {
      if (!cancelled) setMachineName(name);
    });
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    const ticket = (params.get("ticket") || "").trim();
    if (!ticket) return;
    let cancelled = false;
    (async () => {
      setTicketBusy(true);
      setErr("");
      try {
        const res = await fetch(`${window.location.origin}/api/auth/fleet-exchange`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ticket }),
        });
        const text = await res.text();
        let data: ExchangeRes & { detail?: string } = { token: "", username: "", expires_in: 0 };
        try {
          data = text ? JSON.parse(text) : data;
        } catch {
          /* ignore */
        }
        if (!res.ok) {
          throw new Error(data.detail || res.statusText || "兑换失败");
        }
        if (cancelled) return;
        setSession(data.token, data.username, data.expires_in);
        nav("/plan", { replace: true });
      } catch (ex) {
        if (!cancelled) {
          setErr(ex instanceof Error ? ex.message : String(ex));
          setTicketBusy(false);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [params, nav]);

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

  if (ticketBusy && !err) {
    return (
      <div className="login-wrap">
        <div className="login-box">
          <p className="meta">中控免密登录中…</p>
        </div>
      </div>
    );
  }

  return (
    <div className="login-wrap">
      <form className="login-box" onSubmit={onSubmit}>
        <div className="login-title-row">
          <img
            className="login-brand-mark"
            src="/icons/brand.png"
            alt="比特骆驼"
            width={48}
            height={48}
          />
          <h1>
            比特骆驼自动化对冲系统
            {machineName ? (
              <span className="brand-machine">【{machineName}】</span>
            ) : null}
          </h1>
        </div>
        {err ? <div className="err">{err}</div> : null}
        <div className="field">
          <label htmlFor="user">用户名</label>
          <input
            id="user"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoComplete="username"
            required
          />
        </div>
        <div className="field">
          <label htmlFor="pass">密码</label>
          <input
            id="pass"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
            required
          />
        </div>
        <button className="btn block" type="submit" disabled={loading}>
          {loading ? "登录中…" : "登录"}
        </button>
      </form>
    </div>
  );
}
