import React, { createContext, useContext, useState } from 'react';
import { CartItem, Product, ProductLicense } from '../types';
import { useToast } from './ToastContext';

interface CartContextType {
  cart: CartItem[];
  addToCart: (product: Product, license?: ProductLicense) => void;
  removeFromCart: (cartId: string) => void;
  clearCart: () => void;
  cartTotal: number;
  itemCount: number;
}

const CartContext = createContext<CartContextType | undefined>(undefined);

export const useCart = () => {
  const context = useContext(CartContext);
  if (!context) {
    throw new Error('useCart must be used within a CartProvider');
  }
  return context;
};

export const CartProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const { addToast } = useToast();
  const [cart, setCart] = useState<CartItem[]>([]);

  const addToCart = (product: Product, license?: ProductLicense) => {
    // Generate a unique ID for the cart item (productID + licenseID)
    // This allows adding the same product with different licenses
    const licenseId = license ? license.id : 'standard';
    const existingItem = cart.find(
      (item) =>
        item.id === product.id && item.selectedLicense?.id === license?.id,
    );

    if (existingItem) {
      addToast('Item already in cart', 'info');
      return;
    }

    const newItem: CartItem = {
      ...product,
      cartId: `${product.id}-${licenseId}-${Date.now()}`,
      selectedLicense: license,
    };

    setCart((prev) => [...prev, newItem]);
    addToast(`${product.title} added to cart`, 'success');
  };

  const removeFromCart = (cartId: string) => {
    setCart((prev) => prev.filter((item) => item.cartId !== cartId));
  };

  const clearCart = () => {
    setCart([]);
  };

  const cartTotal = cart.reduce((acc, item) => {
    const price = item.selectedLicense
      ? item.selectedLicense.price
      : item.price;
    return acc + price;
  }, 0);

  return (
    <CartContext.Provider
      value={{
        cart,
        addToCart,
        removeFromCart,
        clearCart,
        cartTotal,
        itemCount: cart.length,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};
