import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export interface CartItem {
  id: string
  name: string
  activeIngredient: string
  lab: string
  batch: string
  expiry: string
  vendorId: string
  vendorName: string
  unitPrice: number
  quantity: number
}

interface CartState {
  items: CartItem[]
  addItem: (item: Omit<CartItem, 'quantity'>, quantity?: number) => void
  updateQuantity: (id: string, quantity: number) => void
  removeItem: (id: string) => void
  clearVendor: (vendorId: string) => void
  clearAll: () => void
}

export const useCartStore = create<CartState>()(
  persist(
    (set, get) => ({
      items: [],
      addItem: (item, quantity = 1) => {
        set((state) => {
          const exists = state.items.find((i) => i.id === item.id)
          if (exists) {
            return {
              items: state.items.map((i) =>
                i.id === item.id ? { ...i, quantity: i.quantity + quantity } : i
              )
            }
          }
          return { items: [...state.items, { ...item, quantity }] }
        })
      },
      updateQuantity: (id, quantity) =>
        set((state) => ({
          items: state.items.map((i) => (i.id === id ? { ...i, quantity } : i))
        })),
      removeItem: (id) => set((state) => ({ items: state.items.filter((i) => i.id !== id) })),
      clearVendor: (vendorId) =>
        set((state) => ({ items: state.items.filter((i) => i.vendorId !== vendorId) })),
      clearAll: () => set({ items: [] })
    }),
    {
      name: 'mp-cart-storage',
      version: 1
    }
  )
)

export const selectGroupedCart = (state: CartState) => {
  const groups = state.items.reduce<Record<string, { vendorName: string; items: CartItem[]; total: number }>>(
    (acc, item) => {
      const current = acc[item.vendorId] ?? { vendorName: item.vendorName, items: [], total: 0 }
      current.items.push(item)
      current.total += item.quantity * item.unitPrice
      acc[item.vendorId] = current
      return acc
    },
    {}
  )
  return groups
}

export const selectCartSummary = (state: CartState) => {
  const totalItems = state.items.reduce((acc, item) => acc + item.quantity, 0)
  const totalValue = state.items.reduce((acc, item) => acc + item.quantity * item.unitPrice, 0)
  return { totalItems, totalValue }
}
