'use client';
import { createContext, useContext, useState, useCallback, ReactNode } from 'react';

export type PaymentMethod = 'immediate' | 'deferred' | 'installment';

export interface CartItem {
  id: string;
  productId: string;
  name: string;
  qty: number;
  minQty: number;
  unit: string;
  price: number;
  paymentMethod: PaymentMethod;
  supplierId: string;
  supplierName: string;
  image?: string;
}

interface CartContextType {
  items: CartItem[];
  addItem: (item: Omit<CartItem, 'id'>) => void;
  removeItem: (id: string) => void;
  updateQty: (id: string, qty: number) => void;
  updatePaymentMethod: (id: string, method: PaymentMethod) => void;
  clearCart: () => void;
  clearSupplierCart: (supplierId: string) => void;
  getItemsBySupplier: (supplierId: string) => CartItem[];
  getSupplierTotal: (supplierId: string) => number;
  getGrandTotal: () => number;
  getItemCount: () => number;
}

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

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

  const addItem = useCallback((item: Omit<CartItem, 'id'>) => {
    setItems(prev => {
      const existing = prev.find(i => 
        i.productId === item.productId && 
        i.paymentMethod === item.paymentMethod &&
        i.supplierId === item.supplierId
      );
      if (existing) {
        return prev.map(i => 
          i.id === existing.id 
            ? { ...i, qty: i.qty + item.qty }
            : i
        );
      }
      return [...prev, { ...item, id: Date.now().toString() + Math.random() }];
    });
  }, []);

  const removeItem = useCallback((id: string) => {
    setItems(prev => prev.filter(i => i.id !== id));
  }, []);

  const updateQty = useCallback((id: string, qty: number) => {
    setItems(prev => {
      const item = prev.find(i => i.id === id);
      if (!item) return prev;
      const min = typeof item.minQty === 'number' && item.minQty > 0 ? item.minQty : 1;
      const safeQty = Math.max(min, qty);
      return prev.map(i => i.id === id ? { ...i, qty: safeQty } : i);
    });
  }, []);

  const updatePaymentMethod = useCallback((id: string, method: PaymentMethod) => {
    setItems(prev => prev.map(i => i.id === id ? { ...i, paymentMethod: method } : i));
  }, []);

  const clearCart = useCallback(() => {
    setItems([]);
  }, []);

  const clearSupplierCart = useCallback((supplierId: string) => {
    setItems(prev => prev.filter(i => i.supplierId !== supplierId));
  }, []);

  const getItemsBySupplier = useCallback((supplierId: string) => {
    return items.filter(i => i.supplierId === supplierId);
  }, [items]);

  const getSupplierTotal = useCallback((supplierId: string) => {
    return items
      .filter(i => i.supplierId === supplierId)
      .reduce((sum, i) => sum + (i.price * i.qty), 0);
  }, [items]);

  const getGrandTotal = useCallback(() => {
    return items.reduce((sum, i) => sum + (i.price * i.qty), 0);
  }, [items]);

  const getItemCount = useCallback(() => {
    return items.reduce((count, i) => count + i.qty, 0);
  }, [items]);

  return (
    <CartContext.Provider value={{
      items,
      addItem,
      removeItem,
      updateQty,
      updatePaymentMethod,
      clearCart,
      clearSupplierCart,
      getItemsBySupplier,
      getSupplierTotal,
      getGrandTotal,
      getItemCount,
    }}>
      {children}
    </CartContext.Provider>
  );
}

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