'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Album } from './types';

interface CartItem {
  album: Album;
  quantity: number;
}

interface CartContextType {
  cartItems: CartItem[];
  addToCart: (album: Album) => void;
  removeFromCart: (albumId: string) => void;
  clearCart: () => void;
  getCartTotal: () => number;
  getCartCount: () => number;
  isInCart: (albumId: string) => boolean;
}

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

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

  // Load cart from localStorage on mount
  useEffect(() => {
    const savedCart = localStorage.getItem('cart');
    if (savedCart) {
      setCartItems(JSON.parse(savedCart));
    }
  }, []);

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

  const addToCart = (album: Album) => {
    setCartItems((prev) => {
      const existingItem = prev.find((item) => item.album.id === album.id);
      if (existingItem) {
        // Already in cart, don't add again
        return prev;
      }
      return [...prev, { album, quantity: 1 }];
    });
  };

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

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

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

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

  const isInCart = (albumId: string) => {
    return cartItems.some((item) => item.album.id === albumId);
  };

  return (
    <CartContext.Provider
      value={{
        cartItems,
        addToCart,
        removeFromCart,
        clearCart,
        getCartTotal,
        getCartCount,
        isInCart,
      }}
    >
      {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;
}
