import React, { useState, useEffect } from 'react'
import { likeAPI, API_BASE_URL } from '../api'
import '../styles/matches.css'

export default function Matches({ onNavigateToChat }) {
  const [matches, setMatches] = useState([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    loadMatches()
  }, [])

  const loadMatches = async () => {
    try {
      setIsLoading(true)
      const response = await likeAPI.getMatches()
      setMatches(response.data || [])
    } catch (err) {
      setError('Failed to load matches')
    } finally {
      setIsLoading(false)
    }
  }

  const handleStartChat = () => {
    onNavigateToChat()
  }

  if (isLoading) {
    return <div className="matches">Loading matches...</div>
  }

  if (matches.length === 0) {
    return (
      <div className="matches">
        <div className="empty-state">
          <h2>No matches yet</h2>
          <p>Keep swiping to find your perfect match!</p>
          <a href="/discover">Discover more</a>
        </div>
      </div>
    )
  }

  return (
    <div className="matches">
      <h1>Your Matches</h1>
      {error && <div className="error-message">{error}</div>}

      <div className="matches-grid">
        {matches.map((match) => (
          <div key={match.user_id} className="match-card">
            {match.photo && (
              <img 
                src={`${API_BASE_URL}/media/${match.photo}`} 
                alt={match.display_name}
                className="match-card-photo"
              />
            )}
            <h3>{match.display_name}</h3>
            <button onClick={handleStartChat}>
              Message
            </button>
          </div>
        ))}
      </div>
    </div>
  )
}
