import type { ReactElement } from "react";
import { FormEvent, useState } from "react";

interface LoginShellProps {
  error: string | null;
  onLogin(username: string, password: string): Promise<void>;
}

export function LoginShell({ error, onLogin }: LoginShellProps): ReactElement {
  const [username, setUsername] = useState("admin");
  const [password, setPassword] = useState("hwlab2026");
  const [pending, setPending] = useState(false);

  async function submit(event: FormEvent<HTMLFormElement>): Promise<void> {
    event.preventDefault();
    setPending(true);
    try {
      await onLogin(username, password);
    } finally {
      setPending(false);
    }
  }

  return (
    <section className="login-shell" id="login-shell" data-auth-login aria-labelledby="login-title">
      <div className="login-panel">
        <div className="login-heading">
          <p className="eyebrow">HWLAB</p>
          <h1 id="login-title">云工作台登录</h1>
          <p>请输入账号和密码。</p>
        </div>
        <form className="login-form" id="login-form" autoComplete="on" onSubmit={submit}>
          <label>
            <span>用户名</span>
            <input id="login-username" name="username" type="text" autoComplete="username" inputMode="text" required value={username} onChange={(event) => setUsername(event.currentTarget.value)} />
          </label>
          <label>
            <span>密码</span>
            <input id="login-password" name="password" type="password" autoComplete="current-password" required value={password} onChange={(event) => setPassword(event.currentTarget.value)} />
          </label>
          <p className="login-error" id="login-error" role="alert" hidden={!error}>{error}</p>
          <button className="login-submit" id="login-submit" type="submit" disabled={pending}>{pending ? "登录中" : "登录"}</button>
        </form>
      </div>
    </section>
  );
}
