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

export function LoginPage() {
  const nav = useNavigate();
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setBusy(true);
    try {
      await login(password);
      nav('/', { replace: true });
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败');
    } finally {
      setBusy(false);
    }
  }

  return (
    <main>
      <div className="brand">
        <img className="brand-logo" src="/logo.png" alt="" width={72} height={72} />
        <h1>Sprout2FA</h1>
      </div>
      <p className="sub">输入应用密码以继续。首次使用默认密码请在部署说明中查看。</p>
      <div className="card">
        <form onSubmit={onSubmit}>
          <div className="field">
            <label htmlFor="pw">密码</label>
            <input
              id="pw"
              type="password"
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="应用密码"
              required
            />
          </div>
          {error ? <p className="error">{error}</p> : null}
          <button className="btn" type="submit" disabled={busy} style={{ width: '100%', marginTop: 8 }}>
            {busy ? '验证中…' : '进入'}
          </button>
        </form>
      </div>
    </main>
  );
}
