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

interface BasketItem {
    itemId: string;
    quantity: number;
}

interface BasketContextType {
    basket: BasketItem[];
    addToBasket: (itemId: string, quantity: number) => void;
    clearBasket: () => void;
}

const BasketContext = createContext<BasketContextType | undefined>(undefined);

export const BasketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [basket, setBasket] = useState<BasketItem[]>([]);

    const addToBasket = (itemId: string, quantity: number) => {
        setBasket((prevBasket) => {
            const existingItem = prevBasket.find((item) => item.itemId === itemId);
            if (existingItem) {
                // Update quantity if item already exists
                return prevBasket.map((item) =>
                    item.itemId === itemId
                        ? { ...item, quantity: item.quantity + quantity }
                        : item
                );
            }
            // Add new item to basket
            return [...prevBasket, { itemId, quantity }];
        });
    };

    const clearBasket = () => {
        setBasket([]);
    };

    return (
        <BasketContext.Provider value={{ basket, addToBasket, clearBasket }}>
            {children}
        </BasketContext.Provider>
    );
};

export const useBasket = () => {
    const context = useContext(BasketContext);
    if (!context) {
        throw new Error('useBasket must be used within a BasketProvider');
    }
    return context;
};