import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import type { LoginRequest } from '@_api/auth/authTypes';
import { useAuth } from '../context/AuthContext';

const LoginPage: React.FC = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  const from = location.state?.from?.pathname || '/';

  const handleLogin = async () => {
    try {
      const request: LoginRequest = { email, password };
      await login(request);
      
      alert('로그인에 성공했어요!');
      navigate(from, { replace: true });
    } catch (error: any) {
      const message = error.response?.data?.message || '로그인에 실패했어요. 이메일과 비밀번호를 확인해주세요.';
      alert(message);
      console.error('로그인 실패:', error);
      setEmail('');
      setPassword('');
    }
  }

  return (
    <div className="content-container" style={{ width: '300px' }}>
      <h2 className="content-container-title">Login</h2>
      <div className="form-group">
        <input type="email" className="form-control" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} />
      </div>
      <div className="form-group">
        <input type="password" className="form-control" placeholder="Password" value={password} onChange={e => setPassword(e.target.value)} />
      </div>
      <div className="d-flex justify-content-between">
        <button className="btn btn-outline-custom" onClick={() => navigate('/signup')}>Sign Up</button>
        <button className="btn btn-custom" onClick={handleLogin}>Login</button>
      </div>
    </div>
  );
};

export default LoginPage;