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

export default function Discover() {
  const [profiles, setProfiles] = useState([])
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

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

  const loadProfiles = async () => {
    try {
      setIsLoading(true)
      const response = await profileAPI.discoverProfiles()
      setProfiles(response.data || [])
    } catch (err) {
      setError('Failed to load profiles')
    } finally {
      setIsLoading(false)
    }
  }

  const handleLike = async () => {
    if (currentIndex >= profiles.length) return

    const profile = profiles[currentIndex]
    try {
      const response = await likeAPI.likeUser(profile.id)
      if (response.data.is_match) {
        alert(`It's a match with ${profile.display_name}!`)
      }
      nextProfile()
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to like profile')
    }
  }

  const handlePass = () => {
    nextProfile()
  }

  const nextProfile = () => {
    if (currentIndex < profiles.length - 1) {
      setCurrentIndex((prev) => prev + 1)
    } else {
      setError('No more profiles to discover')
    }
  }

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

  if (currentIndex >= profiles.length) {
    return (
      <div className="discover">
        <div className="empty-state">
          <h2>No more profiles</h2>
          <p>Come back later for new matches!</p>
          <button onClick={loadProfiles}>Refresh</button>
        </div>
      </div>
    )
  }

  const profile = profiles[currentIndex]

  return (
    <div className="discover">
      <h1>Discover</h1>
      {error && <div className="error-message">{error}</div>}

      <div className="card-container">
        <div className="profile-card">
          {profile.photos && profile.photos.length > 0 ? (
            <img src={`${API_BASE_URL}/media/${profile.photos[0].file_path}`} alt={profile.display_name} />
          ) : (
            <div className="no-photo">No photo</div>
          )}

          <div className="card-info">
            <h2>
              {profile.display_name}, {profile.age}
            </h2>
            <p className="location">{profile.location}</p>
            {profile.bio && <p className="bio">{profile.bio}</p>}
            {profile.interests && profile.interests.length > 0 && (
              <div className="interests">
                {profile.interests.map((interest) => (
                  <span key={interest} className="interest-tag">
                    {interest}
                  </span>
                ))}
              </div>
            )}
          </div>

          <div className="card-actions">
            <button className="pass-btn" onClick={handlePass}>
              Pass
            </button>
            <button className="like-btn" onClick={handleLike}>
              ♥ Like
            </button>
          </div>
        </div>
      </div>

      <div className="progress">
        Profile {currentIndex + 1} of {profiles.length}
      </div>
    </div>
  )
}
