import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'

type CartType = 'regular' | 'flash'

interface CartItem {
  id: number
  productId: number
  quantity: number
  storeId: number
  addedAt: number
  slotId?: number | null
  deliveryDate?: string | null
}

function getCartKey(cartType: CartType): string {
  return `local-cart-${cartType}`
}

function readCart(cartType: CartType): CartItem[] {
  try {
    const raw = localStorage.getItem(getCartKey(cartType))
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function writeCart(cartType: CartType, items: CartItem[]) {
  localStorage.setItem(getCartKey(cartType), JSON.stringify(items))
}

export function useGetCart(cartType: CartType = 'regular') {
  return useQuery({
    queryKey: [getCartKey(cartType)],
    queryFn: () => {
      const items = readCart(cartType)
      const totalItems = items.reduce((sum, item) => sum + item.quantity, 0)
      const totalAmount = 0 // Amount calculated in components with product data
      return { items, totalItems, totalAmount }
    },
  })
}

export function useAddToCart(cartType: CartType = 'regular') {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({
      productId,
      quantity,
      storeId,
      slotId,
      deliveryDate,
    }: {
      productId: number
      quantity: number
      storeId: number
      slotId?: number | null
      deliveryDate?: string | null
    }) => {
      const items = readCart(cartType)
      const existing = items.find((i) => i.productId === productId)
      if (existing) {
        existing.quantity += quantity
        if (slotId) existing.slotId = slotId
        if (deliveryDate) existing.deliveryDate = deliveryDate
      } else {
        items.push({
          id: Date.now(),
          productId,
          quantity,
          storeId,
          addedAt: Date.now(),
          slotId: slotId ?? null,
          deliveryDate: deliveryDate ?? null,
        })
      }
      writeCart(cartType, items)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [getCartKey(cartType)] })
    },
  })
}

export function useUpdateCartItem(cartType: CartType = 'regular') {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({
      productId,
      quantity,
      slotId,
      deliveryDate,
    }: {
      productId: number
      quantity: number
      slotId?: number | null
      deliveryDate?: string | null
    }) => {
      const items = readCart(cartType)
      const existing = items.find((i) => i.productId === productId)
      if (existing) {
        existing.quantity = quantity
        if (slotId !== undefined) existing.slotId = slotId
        if (deliveryDate !== undefined) existing.deliveryDate = deliveryDate
      }
      writeCart(cartType, items)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [getCartKey(cartType)] })
    },
  })
}

export function useRemoveFromCart(cartType: CartType = 'regular') {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (productId: number) => {
      let items = readCart(cartType)
      items = items.filter((i) => i.productId !== productId)
      writeCart(cartType, items)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [getCartKey(cartType)] })
    },
  })
}

export function clearLocalCart(cartType: CartType = 'regular') {
  localStorage.removeItem(getCartKey(cartType))
}
