"use client"

import React, { createContext, useContext, useState, useCallback } from 'react'

type FavoriteItem = {
  id: number
  title: string
  price: number
}

type FavoritesContextType = {
  items: FavoriteItem[]
  addToFavorites: (item: FavoriteItem) => void
  removeFromFavorites: (id: number) => void
  isFavorite: (id: number) => boolean
  getTotalFavorites: () => number
}

const FavoritesContext = createContext<FavoritesContextType | undefined>(undefined)

export const useFavorites = () => {
  const context = useContext(FavoritesContext)
  if (!context) {
    throw new Error('useFavorites must be used within a FavoritesProvider')
  }
  return context
}

export const FavoritesProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [items, setItems] = useState<FavoriteItem[]>([])

  const addToFavorites = useCallback((newItem: FavoriteItem) => {
    setItems(currentItems => {
      if (!currentItems.some(item => item.id === newItem.id)) {
        return [...currentItems, newItem]
      }
      return currentItems
    })
  }, [])

  const removeFromFavorites = useCallback((id: number) => {
    setItems(currentItems => currentItems.filter(item => item.id !== id))
  }, [])

  const isFavorite = useCallback((id: number) => {
    return items.some(item => item.id === id)
  }, [items])

  const getTotalFavorites = useCallback(() => {
    return items.length
  }, [items])

  return (
    <FavoritesContext.Provider value={{ items, addToFavorites, removeFromFavorites, isFavorite, getTotalFavorites }}>
      {children}
    </FavoritesContext.Provider>
  )
}

