'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import type { FrontendProductSummary } from '@/lib/types';

export interface CartItem {
  id: string; // Unique cart item ID
  product: FrontendProductSummary;
  size: string;
  fabric: string;
  dupatta?: string;
  trousers?: string;
  silkScarf?: boolean;
  quantity: number;
  price: number; // Final calculated price for this item
}

interface CartContextType {
  cartItems: CartItem[];
  addToCart: (item: Omit<CartItem, 'id'>) => void;
  removeFromCart: (itemId: string) => void;
  updateQuantity: (itemId: string, quantity: number) => void;
  clearCart: () => void;
  getCartCount: () => number;
  getCartTotal: () => number;
}

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

export function CartProvider({ children }: { children: ReactNode }) {
  const [cartItems, setCartItems] = useState<CartItem[]>([]);

  // Load cart from localStorage on mount
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const savedCart = localStorage.getItem('cart');
      if (savedCart) {
        try {
          setCartItems(JSON.parse(savedCart));
        } catch (error) {
          console.error('Error loading cart from localStorage:', error);
        }
      }
    }
  }, []);

  // Save cart to localStorage whenever it changes
  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('cart', JSON.stringify(cartItems));
    }
  }, [cartItems]);

  const addToCart = (item: Omit<CartItem, 'id'>) => {
    setCartItems((prev) => {
      // Check if an item with the same product and options already exists
      const existingItemIndex = prev.findIndex(
        (cartItem) =>
          cartItem.product.id === item.product.id &&
          cartItem.size === item.size &&
          cartItem.fabric === item.fabric &&
          cartItem.dupatta === item.dupatta &&
          cartItem.trousers === item.trousers &&
          cartItem.silkScarf === item.silkScarf
      );

      if (existingItemIndex !== -1) {
        // Item exists, update quantity and price
        const existingItem = prev[existingItemIndex];
        const pricePerItem = existingItem.price / existingItem.quantity;
        const newQuantity = existingItem.quantity + item.quantity;
        const newPrice = pricePerItem * newQuantity;

        return prev.map((cartItem, index) =>
          index === existingItemIndex
            ? { ...cartItem, quantity: newQuantity, price: newPrice }
            : cartItem
        );
      } else {
        // New item, add it to cart
        const newItem: CartItem = {
          ...item,
          id: `${item.product.id}-${item.size}-${item.fabric}-${item.dupatta || 'none'}-${item.trousers || 'none'}-${Date.now()}`,
        };
        return [...prev, newItem];
      }
    });
  };

  const removeFromCart = (itemId: string) => {
    setCartItems((prev) => prev.filter((item) => item.id !== itemId));
  };

  const updateQuantity = (itemId: string, quantity: number) => {
    if (quantity <= 0) {
      removeFromCart(itemId);
      return;
    }
    setCartItems((prev) =>
      prev.map((item) => {
        if (item.id === itemId) {
          // Calculate price per item and multiply by new quantity
          const pricePerItem = item.price / item.quantity;
          return { ...item, quantity, price: pricePerItem * quantity };
        }
        return item;
      })
    );
  };

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

  const getCartCount = () => {
    return cartItems.reduce((total, item) => total + item.quantity, 0);
  };

  const getCartTotal = () => {
    return cartItems.reduce((total, item) => total + item.price, 0);
  };

  return (
    <CartContext.Provider
      value={{
        cartItems,
        addToCart,
        removeFromCart,
        updateQuantity,
        clearCart,
        getCartCount,
        getCartTotal,
      }}
    >
      {children}
    </CartContext.Provider>
  );
}

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

