import React, { useState } from 'react'
import { authAPI } from '../api'
import '../styles/auth.css'

export default function Login({ onLoginSuccess, onRegisterClick }) {
  const [emailOrUsername, setEmailOrUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  const handleLogin = async (e) => {
    e.preventDefault()
    setError('')
    setIsLoading(true)

    try {
      const response = await authAPI.login(emailOrUsername, password)
      const { access_token, user_id } = response.data
      
      // Store token and user ID
      localStorage.setItem('token', access_token)
      localStorage.setItem('user_id', user_id)
      
      onLoginSuccess()
    } catch (err) {
      setError(err.response?.data?.detail || 'Login failed')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="auth-container">
      <div className="auth-card">
        <h1>Dating App</h1>
        <h2>Login</h2>
        {error && <div className="error-message">{error}</div>}
        <form onSubmit={handleLogin}>
          <input
            type="text"
            placeholder="Email or Username"
            value={emailOrUsername}
            onChange={(e) => setEmailOrUsername(e.target.value)}
            required
          />
          <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
          <button type="submit" disabled={isLoading}>
            {isLoading ? 'Logging in...' : 'Login'}
          </button>
        </form>
        <p>
          Don't have an account? <button type="button" onClick={onRegisterClick} className="link-button">Register here</button>
        </p>
      </div>
    </div>
  )
}
