import { useState } from "react";
import { LockKeyhole, TerminalSquare } from "lucide-react";
import { api } from "../api.js";

export function LoginPage({ onLogin }) {
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  async function submit(event) {
    event.preventDefault();
    setBusy(true);
    setError("");
    try {
      await api.login(password);
      onLogin();
    } catch (requestError) {
      setError(requestError.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <main className="login-shell">
      <form className="login-panel" onSubmit={submit}>
        <span className="logo login-logo" aria-hidden="true"><TerminalSquare size={18} strokeWidth={1.8} /></span>
        <div>
          <h1>AgentDock</h1>
          <p>AI CLI 管理控制台</p>
        </div>
        <label className="login-field">
          <span>管理员密码</span>
          <span className="login-input-wrap">
            <LockKeyhole size={15} aria-hidden="true" />
            <input
              autoFocus
              autoComplete="current-password"
              type="password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              placeholder="输入管理员密码"
            />
          </span>
        </label>
        {error ? <p className="form-error" role="alert">{error}</p> : null}
        <button className="btn btn-primary" type="submit" disabled={busy || !password}>
          {busy ? "正在验证" : "登录"}
        </button>
        <span className="meta login-meta">仅允许局域网内访问</span>
      </form>
    </main>
  );
}
