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

export default function Register({ onRegisterSuccess, onLoginClick }) {
  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [displayName, setDisplayName] = useState('')
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)

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

    try {
      const response = await authAPI.register(username, email, password, displayName)
      const { access_token, user_id } = response.data
      
      // Store token and user ID
      localStorage.setItem('token', access_token)
      localStorage.setItem('user_id', user_id)
      
      onRegisterSuccess()
    } catch (err) {
      const errorMsg = err.response?.data?.detail || err.message || 'Registration failed'
      setError(errorMsg)
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="auth-container">
      <div className="auth-card">
        <h1>Dating App</h1>
        <h2>Register</h2>
        {error && <div className="error-message">{error}</div>}
        <form onSubmit={handleRegister}>
          <input
            type="text"
            placeholder="Username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            required
          />
          <input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
          <input
            type="text"
            placeholder="Display Name"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            required
          />
          <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
          <button type="submit" disabled={isLoading}>
            {isLoading ? 'Registering...' : 'Register'}
          </button>
        </form>
        <p>
          Already have an account? <button type="button" onClick={onLoginClick} className="link-button">Login here</button>
        </p>
      </div>
    </div>
  )
}
