import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Heart } from 'lucide-react'
import { Link, useNavigate } from 'react-router-dom'
import { getWishlist, removeWishlist } from '../api/client'
import ProductCard from './components/ProductCard'
import { useShop } from '../store/shop'

export default function Wishlist() {
  const { t } = useTranslation()
  const qc = useQueryClient()
  const nav = useNavigate()
  const { custToken } = useShop()
  const { data: items } = useQuery({ queryKey: ['wishlist'], queryFn: getWishlist, enabled: !!custToken })

  if (!custToken) { nav('/account'); return null }
  const list = items || []

  const remove = async (pid: number) => { await removeWishlist(pid).catch(() => {}); qc.invalidateQueries({ queryKey: ['wishlist'] }) }

  return (
    <div className="max-w-6xl mx-auto px-4 py-8">
      <div className="flex items-center gap-2 mb-6"><Heart className="text-bloom" size={22} /><h1 className="font-serif text-2xl font-bold text-blush-900">{t('wishlist.title')}</h1></div>
      {!list.length ? (
        <div className="text-center text-gray-400 py-16">{t('wishlist.empty')} <Link to="/category" className="text-bloom">{t('wishlist.startShopping')}</Link></div>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {list.map((p: any) => (
            <div key={p.id || p.productId} className="relative">
              <ProductCard p={{ ...p, id: p.productId || p.id }} />
              <button onClick={() => remove(p.productId || p.id)} className="absolute top-2 right-2 bg-white/90 rounded-full p-1.5 text-bloom shadow"><Heart size={16} fill="currentColor" /></button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
