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

export default function LikesReceived({ onNotificationsUpdate }) {
  const [likes, setLikes] = useState([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')
  const [profiles, setProfiles] = useState({})

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

  const loadLikesReceived = async () => {
    try {
      setIsLoading(true)
      const response = await likeAPI.getLikesReceived()
      setLikes(response.data || [])
      
      // Fetch profile details for each liker
      const profilesData = {}
      for (const like of response.data || []) {
        try {
          const profileRes = await profileAPI.getProfile(like.user_id)
          profilesData[like.user_id] = profileRes.data
        } catch (err) {
          console.error(`Failed to load profile for user ${like.user_id}`)
        }
      }
      setProfiles(profilesData)
      
      // Notify parent about notifications update
      if (onNotificationsUpdate) {
        onNotificationsUpdate()
      }
    } catch (err) {
      setError('Failed to load likes')
    } finally {
      setIsLoading(false)
    }
  }

  const handleLike = async (userId) => {
    try {
      await likeAPI.likeUser(userId)
      // Remove from likes list after liking back
      setLikes(prev => prev.filter(like => like.user_id !== userId))
      if (onNotificationsUpdate) {
        onNotificationsUpdate()
      }
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to like profile')
    }
  }

  const handlePass = (userId) => {
    // Remove from list without liking
    setLikes(prev => prev.filter(like => like.user_id !== userId))
  }

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

  if (likes.length === 0) {
    return (
      <div className="likes-received">
        <div className="empty-state">
          <h2>No likes yet</h2>
          <p>Keep discovering to get more likes!</p>
        </div>
      </div>
    )
  }

  return (
    <div className="likes-received">
      <h1>People Who Liked You ❤️</h1>
      {error && <div className="error-message">{error}</div>}

      <div className="likes-grid">
        {likes.map((like) => {
          const profile = profiles[like.user_id]
          return (
            <div key={like.user_id} className="like-card">
              <div className="like-card-image">
                {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>

              <div className="like-card-info">
                <h3>{profile?.display_name}, {profile?.age}</h3>
                <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="like-card-actions">
                <button className="pass-btn" onClick={() => handlePass(like.user_id)}>
                  Pass
                </button>
                <button className="like-back-btn" onClick={() => handleLike(like.user_id)}>
                  ❤️ Like Back
                </button>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
