'use client';

import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { WishlistService } from '../services/wishlist.service';
import { LocalWishlistRepository } from '../repositories/local-wishlist.repository';

interface WishlistContextType {
  items: string[];
  addItem: (productId: string) => void;
  removeItem: (productId: string) => void;
  isInWishlist: (productId: string) => boolean;
  hydrated: boolean;
}

const WishlistContext = createContext<WishlistContextType | undefined>(undefined);

const repository = new LocalWishlistRepository();
const service = new WishlistService(repository);

export function WishlistProvider({ children }: { children: React.ReactNode }) {
  const [items, setItems] = useState<string[]>([]);
  const [hydrated, setHydrated] = useState(false);

  useEffect(() => {
    const initialItems = service.getItems();
    setItems(initialItems);
    setHydrated(true);
  }, []);

  const addItem = useCallback((productId: string) => {
    service.addItem(productId);
    setItems(prev => [...new Set([...prev, productId])]);
  }, []);

  const removeItem = useCallback((productId: string) => {
    service.removeItem(productId);
    setItems(prev => prev.filter(id => id !== productId));
  }, []);

  const isInWishlist = useCallback((productId: string) => {
    return items.includes(productId);
  }, [items]);

  const value = {
    items,
    addItem,
    removeItem,
    isInWishlist,
    hydrated,
  };

  return <WishlistContext.Provider value={value}>{children}</WishlistContext.Provider>;
}

export function useWishlist() {
  const context = useContext(WishlistContext);
  if (context === undefined) {
    throw new Error('useWishlist must be used within a WishlistProvider');
  }
  return context;
}
