import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { login } from '../api';
import { useAuth } from '../auth/AuthContext';
import { PasswordInput } from '../components/PasswordInput';
import bokBadge from '../assets/bok-removebg.png';

export const LoginPage: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const { refresh } = useAuth();
  const navigate = useNavigate();

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setBusy(true);
    try {
      const user = await login({ username, password });
      await refresh();
      navigate(user.mustChangePassword ? '/change-password' : '/dashboard', { replace: true });
    } catch (err) {
      setError(err instanceof Error ? err.message : '로그인 실패');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="center-screen">
      <form className="card auth-card" onSubmit={onSubmit}>
        <img src={bokBadge} className="auth-badge" alt="" />
        <h1 className="auth-title">IT센터 출입자관리</h1>
        <p className="auth-sub">시스템에 로그인하세요</p>

        {error && <div className="alert alert-error">{error}</div>}

        <label className="field">
          <span>아이디</span>
          <input
            className="ime-en"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoFocus
            autoCapitalize="off"
            autoCorrect="off"
            spellCheck={false}
          />
        </label>
        <label className="field">
          <span>비밀번호</span>
          <PasswordInput value={password} onChange={(e) => setPassword(e.target.value)} />
        </label>

        <button className="btn-primary full" type="submit" disabled={busy || !username || !password}>
          {busy ? '로그인 중…' : '로그인'}
        </button>

        <p className="hint">테스트 계정: a(관리자) / s(보안) / h(호스트) · 비밀번호 1</p>
      </form>
    </div>
  );
};
