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

export interface CartItem {
  key: string;
  product_id: number;
  variation_id?: number;
  quantity: number;
  name: string;
  price: number;
  image?: string;
  attributes?: Record<string, string>;
  virtual?: boolean;
  downloadable?: boolean;
}

export interface Cart {
  items: CartItem[];
  subtotal: number;
  tax: number;
  shipping: number;
  total: number;
  needs_shipping?: boolean;
  coupon?: {
    code: string;
    discount: number;
  };
  coupons?: {
    code: string;
    discount: number;
    type?: string;
  }[];
  discount_total?: number;
  shipping_total?: number;
}

interface CartStore {
  cart: Cart;
  isOpen: boolean;

  // Actions
  setCart: (cart: Cart) => void;
  addItem: (item: CartItem) => void;
  updateQuantity: (key: string, quantity: number) => void;
  removeItem: (key: string) => void;
  clearCart: () => void;
  openCart: () => void;
  closeCart: () => void;
  toggleCart: () => void;
}

const initialCart: Cart = {
  items: [],
  subtotal: 0,
  tax: 0,
  shipping: 0,
  total: 0,
};

export const useCartStore = create<CartStore>()(
  persist(
    (set) => ({
      cart: initialCart,
      isOpen: false,

      setCart: (cart) => set({ cart }),

      addItem: (item) =>
        set((state) => {
          const existingItem = state.cart.items.find((i) => i.key === item.key);

          if (existingItem) {
            // Update quantity if item exists
            return {
              cart: {
                ...state.cart,
                items: state.cart.items.map((i) =>
                  i.key === item.key
                    ? { ...i, quantity: i.quantity + item.quantity }
                    : i
                ),
              },
            };
          }

          // Add new item
          return {
            cart: {
              ...state.cart,
              items: [...state.cart.items, item],
            },
          };
        }),

      updateQuantity: (key, quantity) =>
        set((state) => ({
          cart: {
            ...state.cart,
            items: state.cart.items.map((item) =>
              item.key === key ? { ...item, quantity } : item
            ),
          },
        })),

      removeItem: (key) =>
        set((state) => ({
          cart: {
            ...state.cart,
            items: state.cart.items.filter((item) => item.key !== key),
          },
        })),

      clearCart: () => set({ cart: initialCart }),

      openCart: () => set({ isOpen: true }),
      closeCart: () => set({ isOpen: false }),
      toggleCart: () => set((state) => ({ isOpen: !state.isOpen })),
    }),
    {
      name: 'woonoow-cart',
      partialize: (state) => ({ cart: state.cart }),
    }
  )
);
