import React, { createContext, useContext, useState } from 'react';
import Item from '../components/Item';

export interface BasketItem {
    item: Item;
    quantity: number;
}

interface BasketContextType {
    basket: BasketItem[];
    addToBasket: (item: Item, 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 = (item: Item, quantity: number) => {
        setBasket((prevBasket) => {
            const existingItem = prevBasket.find((basketItem) => basketItem.item.uuid === item.uuid);
            if (existingItem) {
                // Update quantity if item already exists
                return prevBasket.map((basketItem) =>
                    basketItem.item.uuid === item.uuid
                        ? { ...basketItem, quantity: basketItem.quantity + quantity }
                        : basketItem
                );
            }
            // Add new item to basket
            return [...prevBasket, { item, 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;
};