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

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

  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);
    }
  }

  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>比特骆驼自动化对冲系统</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>
  );
}
