import { useState } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { useAuth } from '../context/useAuth';
import { getSSAFYLoginURL } from '../api/auth';
import './AuthPage.css';

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const justRegistered = location.state?.registered;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!username.trim() || !password) {
      setError('아이디와 비밀번호를 입력해주세요.');
      return;
    }
    setLoading(true);
    try {
      await login(username, password);
      navigate('/', { replace: true });
    } catch (err) {
      setError(err.message || '로그인에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      <div className="login-panel">
        <div className="login-header">
          <h1 className="game-title">One of the plans</h1>
          <p className="game-subtitle">MULTIPLAYER</p>
        </div>

        <form className="login-form" onSubmit={handleSubmit}>
          <div className="input-group">
            <label htmlFor="username">아이디</label>
            <input
              id="username"
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="아이디를 입력하세요"
              autoComplete="username"
              maxLength={50}
            />
          </div>

          <div className="input-group">
            <label htmlFor="password">비밀번호</label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="비밀번호를 입력하세요"
              autoComplete="current-password"
              maxLength={72}
            />
          </div>

          {justRegistered && <p className="login-success">회원가입이 완료되었습니다. 로그인해주세요.</p>}
          {error && <p className="login-error" role="alert">{error}</p>}

          <button type="submit" className="btn-login" disabled={loading}>
            {loading ? '로그인 중...' : '로그인'}
          </button>
        </form>

        <div className="login-divider">
          <span>또는</span>
        </div>

        <button
          type="button"
          className="btn-ssafy"
          onClick={async () => {
            try {
              const data = await getSSAFYLoginURL();
              window.location.href = data.url;
            } catch {
              setError('SSAFY 로그인 URL을 가져올 수 없습니다.');
            }
          }}
        >
          SSAFY 계정으로 로그인
        </button>

        <Link to="/register" className="login-back">계정이 없으신가요? 회원가입</Link>
        <Link to="/" className="login-back">메인으로 돌아가기</Link>
      </div>
    </div>
  );
}
