import React, { useState, useEffect } from 'react'
import { likeAPI, profileAPI, API_BASE_URL } from '../api'
import likeIcon from '../assets/icons/like.svg'
import notLikeIcon from '../assets/icons/notLike.svg'
import '../styles/likes-modal.css'

export default function LikesModal({ isOpen, onClose, onLikesUpdate }) {
  const [likes, setLikes] = useState([])
  const [profiles, setProfiles] = useState({})
  const [isLoading, setIsLoading] = useState(false)
  const [likedProfiles, setLikedProfiles] = useState(new Set())

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

  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)
      
      // Always update parent to sync notification count
      if (onLikesUpdate) {
        onLikesUpdate()
      }
    } catch (err) {
      console.error('Failed to load likes', err)
    } finally {
      setIsLoading(false)
    }
  }

  const handleCloseModal = async () => {
    // Mark all viewed likes as acknowledged in database
    try {
      await likeAPI.acknowledgeLikes()
    } catch (err) {
      console.error('Failed to acknowledge likes', err)
    }
    
    // Update parent notification count when closing
    if (onLikesUpdate) {
      onLikesUpdate()
    }
    onClose()
  }

  const handleLike = async (userId) => {
    try {
      await likeAPI.likeUser(userId)
      setLikedProfiles(prev => new Set(prev).add(userId))
      // Remove from likes list after a short delay
      setTimeout(() => {
        setLikes(prev => prev.filter(like => like.user_id !== userId))
      }, 300)
      if (onLikesUpdate) {
        onLikesUpdate()
      }
    } catch (err) {
      console.error('Failed to like profile', err)
    }
  }

  const handlePass = (userId) => {
    setLikes(prev => prev.filter(like => like.user_id !== userId))
  }

  if (!isOpen) return null

  return (
    <div className="likes-modal-overlay" onClick={handleCloseModal}>
      <div className="likes-modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="likes-modal-header">
          <h2>❤️ New Likes</h2>
          <button className="likes-modal-close" onClick={handleCloseModal}>&times;</button>
        </div>

        <div className="likes-modal-body">
          {isLoading ? (
            <p className="loading">Loading...</p>
          ) : likes.length === 0 ? (
            <p className="no-likes">No new likes yet</p>
          ) : (
            <div className="likes-list">
              {likes.map((like) => {
                const profile = profiles[like.user_id]
                return (
                  <div key={like.user_id} className="like-item">
                    <div className="like-item-photo">
                      {profile?.photos && profile.photos.length > 0 ? (
                        <img 
                          src={`${API_BASE_URL}/media/${profile.photos[0].file_path}`} 
                          alt={profile?.display_name}
                        />
                      ) : (
                        <div className="like-item-placeholder">
                          {profile?.display_name?.charAt(0).toUpperCase()}
                        </div>
                      )}
                    </div>
                    <div className="like-item-info">
                      <h4>{profile?.display_name}, {profile?.age}</h4>
                      <p>{profile?.location}</p>
                    </div>
                    <div className="like-item-actions">
                      <button 
                        className="like-item-pass"
                        onClick={() => handlePass(like.user_id)}
                        title="Skip"
                      >
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <line x1="18" y1="6" x2="6" y2="18"></line>
                          <line x1="6" y1="6" x2="18" y2="18"></line>
                        </svg>
                      </button>
                      <button 
                        className={`like-item-like ${likedProfiles.has(like.user_id) ? 'already-liked' : ''}`}
                        onClick={() => handleLike(like.user_id)}
                        title={likedProfiles.has(like.user_id) ? 'Liked' : 'Like'}
                      >
                        <img src={likedProfiles.has(like.user_id) ? likeIcon : notLikeIcon} alt="Like" className="like-button-icon" />
                      </button>
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
