import React, { useState, useEffect, useContext } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '../api'
import { AuthContext } from '../context/AuthContext'
import ProductCard from '../components/ProductCard'
import '../styles/global.css'

export default function Wishlist() {
  const navigate = useNavigate()
  const { token } = useContext(AuthContext)
  const [wishlistItems, setWishlistItems] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!token) {
      navigate('/login')
    } else {
      fetchWishlist()
    }
  }, [token, navigate])

  const fetchWishlist = async () => {
    try {
      const response = await api.get('/wishlist')
      setWishlistItems(response.data)
    } catch (error) {
      console.error('Error fetching wishlist:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleRemoveFromWishlist = async (productId) => {
    try {
      await api.delete(`/wishlist/${productId}`)
      setWishlistItems(
        wishlistItems.filter((item) => item.id !== productId)
      )
    } catch (error) {
      console.error('Error removing from wishlist:', error)
    }
  }

  if (loading) return <div className="loading">Loading...</div>

  return (
    <div className="wishlist-page">
      <h1>My Wishlist</h1>

      {wishlistItems.length === 0 ? (
        <div className="empty-state">
          <p>Your wishlist is empty</p>
          <a href="/products" className="btn">
            Browse Products
          </a>
        </div>
      ) : (
        <div className="wishlist-container">
          <div className="grid">
            {wishlistItems.map((product) => (
              <div key={product.id} className="wishlist-item">
                <ProductCard product={product} />
                <button
                  className="btn btn-small btn-danger"
                  onClick={() => handleRemoveFromWishlist(product.id)}
                >
                  Remove from Wishlist
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
