"use client"

import {
  createContext,
  useContext,
  useReducer,
  type ReactNode,
} from "react"
import type { Cart, CartItem } from "@/types/cart"
import type { Product } from "@/types/product"

type CartAction =
  | { type: "ADD_ITEM"; payload: { product: Product; size: string; color: string } }
  | { type: "REMOVE_ITEM"; payload: { productId: string; size: string; color: string } }
  | { type: "UPDATE_QUANTITY"; payload: { productId: string; size: string; color: string; quantity: number } }
  | { type: "CLEAR_CART" }

function calcTotal(items: CartItem[]): number {
  return items.reduce((sum, i) => sum + i.product.price * i.quantity, 0)
}

function cartReducer(state: Cart, action: CartAction): Cart {
  switch (action.type) {
    case "ADD_ITEM": {
      const { product, size, color } = action.payload
      const match = (i: CartItem) =>
        i.product.id === product.id && i.size === size && i.color === color
      const existing = state.items.find(match)
      const items = existing
        ? state.items.map((i) => (match(i) ? { ...i, quantity: i.quantity + 1 } : i))
        : [...state.items, { product, quantity: 1, size, color }]
      return { items, total: calcTotal(items) }
    }
    case "REMOVE_ITEM": {
      const { productId, size, color } = action.payload
      const items = state.items.filter(
        (i) => !(i.product.id === productId && i.size === size && i.color === color)
      )
      return { items, total: calcTotal(items) }
    }
    case "UPDATE_QUANTITY": {
      const { productId, size, color, quantity } = action.payload
      const match = (i: CartItem) =>
        i.product.id === productId && i.size === size && i.color === color
      const items =
        quantity === 0
          ? state.items.filter((i) => !match(i))
          : state.items.map((i) => (match(i) ? { ...i, quantity } : i))
      return { items, total: calcTotal(items) }
    }
    case "CLEAR_CART":
      return { items: [], total: 0 }
  }
}

type CartContextValue = {
  cart: Cart
  addItem: (product: Product, size: string, color: string) => void
  removeItem: (productId: string, size: string, color: string) => void
  updateQuantity: (productId: string, size: string, color: string, quantity: number) => void
  clearCart: () => void
}

const CartContext = createContext<CartContextValue | null>(null)

export function CartProvider({ children }: { children: ReactNode }) {
  const [cart, dispatch] = useReducer(cartReducer, { items: [], total: 0 })

  const addItem = (product: Product, size: string, color: string) =>
    dispatch({ type: "ADD_ITEM", payload: { product, size, color } })

  const removeItem = (productId: string, size: string, color: string) =>
    dispatch({ type: "REMOVE_ITEM", payload: { productId, size, color } })

  const updateQuantity = (productId: string, size: string, color: string, quantity: number) =>
    dispatch({ type: "UPDATE_QUANTITY", payload: { productId, size, color, quantity } })

  const clearCart = () => dispatch({ type: "CLEAR_CART" })

  return (
    <CartContext.Provider value={{ cart, addItem, removeItem, updateQuantity, clearCart }}>
      {children}
    </CartContext.Provider>
  )
}

export function useCartStore() {
  const ctx = useContext(CartContext)
  if (!ctx) throw new Error("useCartStore must be used within CartProvider")
  return ctx
}
