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

export default function Discover({ onNotificationsUpdate, onNavigateToChat }) {
  const [profiles, setProfiles] = useState([])
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')
  const [likedProfiles, setLikedProfiles] = useState(new Set())
  const [showMatchModal, setShowMatchModal] = useState(false)
  const [matchName, setMatchName] = useState('')

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

  const loadProfiles = async () => {
    try {
      setIsLoading(true)
      const response = await profileAPI.discoverProfiles()
      setProfiles(response.data || [])
      
      // Load all profiles this user has already liked
      const likedResponse = await likeAPI.getLikedProfiles()
      const likedIds = new Set(likedResponse.data?.liked_ids || [])
      setLikedProfiles(likedIds)
      
      // Notify parent about notifications update
      if (onNotificationsUpdate) {
        onNotificationsUpdate()
      }
    } catch (err) {
      setError('Failed to load profiles')
    } finally {
      setIsLoading(false)
    }
  }

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

    const profile = profiles[currentIndex]
    const isAlreadyLiked = likedProfiles.has(profile.id)

    try {
      if (isAlreadyLiked) {
        // Unlike
        await likeAPI.unlikeUser(profile.id)
        setLikedProfiles(prev => {
          const newSet = new Set(prev)
          newSet.delete(profile.id)
          return newSet
        })
      } else {
        // Like
        const response = await likeAPI.likeUser(profile.id)
        setLikedProfiles(prev => new Set(prev).add(profile.id))
        if (response.data.is_match) {
          setMatchName(profile.display_name)
          setShowMatchModal(true)
        }
      }
      // Update notifications
      if (onNotificationsUpdate) {
        onNotificationsUpdate()
      }
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to update like')
    }
  }

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

  const previousProfile = () => {
    setCurrentIndex((prev) => (prev > 0 ? prev - 1 : profiles.length - 1))
  }

  const nextProfile = () => {
    setCurrentIndex((prev) => (prev < profiles.length - 1 ? prev + 1 : 0))
  }

  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]
  const isAlreadyLiked = likedProfiles.has(profile.id)

  // Get current + next 2 profiles with infinite loop wrapping
  const getCardAtIndex = (idx) => {
    return profiles[(currentIndex + idx) % profiles.length]
  }
  const cardsToShow = [
    getCardAtIndex(0),
    getCardAtIndex(1),
    getCardAtIndex(2)
  ]

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

      <div className="card-container">
        <button 
          className="nav-arrow nav-arrow-left" 
          onClick={previousProfile}
          title="Previous profile"
        >
          ◀
        </button>

        {cardsToShow.map((prof, idx) => {
          const isCurrentLiked = likedProfiles.has(prof.id)
          return (
            <div key={prof.id} className="profile-card" style={{zIndex: 10 - idx}}>
              {idx === 0 && isCurrentLiked && <div className="liked-badge">❤️ Liked</div>}
              
              {prof.photos && prof.photos.length > 0 ? (
                <img src={`${API_BASE_URL}/media/${prof.photos[0].file_path}`} alt={prof.display_name} />
              ) : (
                <div className="no-photo">No photo</div>
              )}

              {idx === 0 && (
                <>
                  <div className="card-info">
                    <h2>
                      {prof.display_name}, {prof.age}
                    </h2>
                    <p className="location">{prof.location}</p>
                    {prof.bio && <p className="bio">{prof.bio}</p>}
                    {prof.interests && prof.interests.length > 0 && (
                      <div className="interests">
                        {prof.interests.map((interest) => (
                          <span key={interest} className="interest-tag">
                            {interest}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                  <div className="card-actions">
                    <button className="pass-btn" onClick={handlePass} title="Pass">
                      <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-btn ${isCurrentLiked ? 'already-liked' : ''}`}
                      onClick={handleLike}
                      title={isCurrentLiked ? 'Unlike' : 'Like'}
                    >
                      <img src={isCurrentLiked ? likeIcon : notLikeIcon} alt="Like" className="like-button-icon" />
                    </button>
                  </div>
                </>
              )}
            </div>
          )
        })}

        <button 
          className="nav-arrow nav-arrow-right" 
          onClick={nextProfile}
          title="Next profile"
        >
          ▶
        </button>
      </div>

      {/* <div className="profile-counter">
        Profile {currentIndex + 1} of {profiles.length}
      </div> */}

      <Modal
        isOpen={showMatchModal}
        title="It's a Match! 🎉"
        message={`You and ${matchName} liked each other! Start chatting now.`}
        confirmText="Go to Chat"
        cancelText="Keep Discovering"
        onConfirm={() => {
          setShowMatchModal(false)
          if (onNavigateToChat) {
            onNavigateToChat()
          }
        }}
        onCancel={() => {
          setShowMatchModal(false)
          nextProfile()
        }}
      />
    </div>
  )
}
