import { create } from 'zustand';
import type { Product, CartItem, PaymentMethod } from '@/types';

interface CartState {
  items: CartItem[];
  paymentMethod: PaymentMethod | null;
  amountReceived: number;
  notes: string;

  // Computed
  subtotal: number;
  discountAmount: number;
  taxAmount: number;
  total: number;
  itemCount: number;

  // Actions
  addItem: (product: Product, quantity?: number) => void;
  removeItem: (productId: string) => void;
  updateQuantity: (productId: string, quantity: number) => void;
  applyItemDiscount: (productId: string, discountPercent: number) => void;
  setPaymentMethod: (method: PaymentMethod) => void;
  setAmountReceived: (amount: number) => void;
  setNotes: (notes: string) => void;
  clear: () => void;
}

const calculateTotals = (items: CartItem[]) => {
  // Subtotal = sum of line subtotals (already with discount applied)
  const subtotal = items.reduce((sum, item) => sum + item.subtotal, 0);
  // Discount amount = original price - discounted price
  const discountAmount = items.reduce((sum, item) => {
    const originalPrice = item.unitPrice * item.quantity;
    return sum + (originalPrice - item.subtotal);
  }, 0);
  // Tax included in price (16% IVA)
  const taxRate = 0.16;
  const taxAmount = subtotal - (subtotal / (1 + taxRate));
  const total = subtotal;
  const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);

  return { subtotal, discountAmount, taxAmount, total, itemCount };
};

export const useCartStore = create<CartState>((set, get) => ({
  items: [],
  paymentMethod: null,
  amountReceived: 0,
  notes: '',
  subtotal: 0,
  discountAmount: 0,
  taxAmount: 0,
  total: 0,
  itemCount: 0,

  addItem: (product, quantity = 1) => {
    const { items } = get();
    const existingIndex = items.findIndex((item) => item.product.id === product.id);

    let newItems: CartItem[];

    if (existingIndex >= 0) {
      // Update existing item
      newItems = items.map((item, index) => {
        if (index === existingIndex) {
          const newQty = item.quantity + quantity;
          const discountMultiplier = 1 - (item.discountPercent / 100);
          return {
            ...item,
            quantity: newQty,
            subtotal: newQty * item.unitPrice * discountMultiplier,
          };
        }
        return item;
      });
    } else {
      // Add new item
      const newItem: CartItem = {
        product,
        quantity,
        unitPrice: product.price,
        discountPercent: 0,
        subtotal: quantity * product.price,
      };
      newItems = [...items, newItem];
    }

    set({ items: newItems, ...calculateTotals(newItems) });
  },

  removeItem: (productId) => {
    const newItems = get().items.filter((item) => item.product.id !== productId);
    set({ items: newItems, ...calculateTotals(newItems) });
  },

  updateQuantity: (productId, quantity) => {
    if (quantity <= 0) {
      get().removeItem(productId);
      return;
    }

    const newItems = get().items.map((item) => {
      if (item.product.id === productId) {
        const discountMultiplier = 1 - (item.discountPercent / 100);
        return {
          ...item,
          quantity,
          subtotal: quantity * item.unitPrice * discountMultiplier,
        };
      }
      return item;
    });
    set({ items: newItems, ...calculateTotals(newItems) });
  },

  applyItemDiscount: (productId, discountPercent) => {
    const newItems = get().items.map((item) => {
      if (item.product.id === productId) {
        const discountMultiplier = 1 - (discountPercent / 100);
        return {
          ...item,
          discountPercent,
          subtotal: item.quantity * item.unitPrice * discountMultiplier,
        };
      }
      return item;
    });
    set({ items: newItems, ...calculateTotals(newItems) });
  },

  setPaymentMethod: (method) => set({ paymentMethod: method }),

  setAmountReceived: (amount) => set({ amountReceived: amount }),

  setNotes: (notes) => set({ notes }),

  clear: () =>
    set({
      items: [],
      paymentMethod: null,
      amountReceived: 0,
      notes: '',
      subtotal: 0,
      discountAmount: 0,
      taxAmount: 0,
      total: 0,
      itemCount: 0,
    }),
}));
