import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './admin.css';

export default function AdminLogin() {
  const [form, setForm] = useState({ username: '', password: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(''); setLoading(true);
    try {
      const res = await fetch('/api/admin/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.message || '로그인 실패'); return; }
      localStorage.setItem('admin_token', data.token);
      localStorage.setItem('admin_user', JSON.stringify({ username: data.username, displayName: data.displayName }));
      navigate('/admin/dashboard');
    } catch {
      setError('서버 연결 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="admin-login-page">
      <div className="admin-login-box">
        <div className="login-logo">
          <span className="login-badge">ADMIN</span>
          <h1>(주)지오정보기술</h1>
          <p>홈페이지 관리자 시스템</p>
        </div>
        {error && <div className="login-error">⚠ {error}</div>}
        <form onSubmit={handleSubmit}>
          <div className="login-input-group">
            <label>아이디</label>
            <input
              type="text" placeholder="관리자 아이디" value={form.username} required
              onChange={e => setForm(p => ({ ...p, username: e.target.value }))}
            />
          </div>
          <div className="login-input-group">
            <label>비밀번호</label>
            <input
              type="password" placeholder="비밀번호" value={form.password} required
              onChange={e => setForm(p => ({ ...p, password: e.target.value }))}
            />
          </div>
          <button type="submit" className="login-btn" disabled={loading}>
            {loading ? '로그인 중...' : '로그인'}
          </button>
        </form>
        <p style={{ textAlign: 'center', marginTop: 20, fontSize: 12, color: '#94a3b8' }}>
          홈페이지로 돌아가기: <a href="/" style={{ color: '#4f6ef7' }}>메인 페이지</a>
        </p>
      </div>
    </div>
  );
}
