import React from 'react'
import { p, div, Quantifier, MiniQuantifier } from 'web-components'
import { useGetCart, useUpdateCartItem, useRemoveFromCart, useAddToCart } from '../hooks/cart-query-hooks'
import { useCartStore } from '../lib/stores/cart-store'
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
import dayjs from 'dayjs'
import { Truck, ShoppingCart, ImageOff } from 'lucide-react'

interface ProductCardProps {
  item: any
  onPress?: () => void
  showDeliveryInfo?: boolean
  miniView?: boolean
  useAddToCartDialog?: boolean
}

const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => {
  if (unit?.toLowerCase() === 'kg' && quantity < 1) {
    return { value: `${Math.round(quantity * 1000)} g`, display: `${Math.round(quantity * 1000)}g` }
  }
  return { value: `${quantity} ${unit}(s)`, display: `${quantity}${unit}` }
}

export function ProductCard({
  item,
  onPress,
  showDeliveryInfo = true,
  miniView = false,
  useAddToCartDialog = false,
}: ProductCardProps) {
  const [imageError, setImageError] = React.useState(false)
  const [imageLoading, setImageLoading] = React.useState(true)

  const imageUri = item.images?.[0]

  const { data: cartData } = useGetCart('regular')
  const { getQuickestSlot } = useProductSlotIdentifier()
  const { setAddedToCartProduct } = useCartStore()
  const updateCartItem = useUpdateCartItem('regular')
  const removeFromCart = useRemoveFromCart('regular')
  const addToCart = useAddToCart('regular')

  // Find current quantity from cart data
  const cartItem = cartData?.items?.find((cartItem: any) => cartItem.productId === item.id)
  const quantity = cartItem?.quantity || 0

  // Get slots data from central store
  const slots = useCentralSlotStore((state) => state.slots)
  const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)

  // Create slot lookup map
  const slotMap = React.useMemo(() => {
    const map: Record<number, any> = {}
    slots?.forEach((slot: any) => {
      map[slot.id] = slot
    })
    return map
  }, [slots])

  // Get cart item's slot delivery time if item is in cart
  const cartSlot = cartItem?.slotId ? slotMap[cartItem.slotId] : null
  const displayDeliveryDate = cartSlot?.deliveryTime || item.nextDeliveryDate

  // Precompute the next slot and determine display out of stock status
  const slotId = getQuickestSlot(item.id)
  const productSlotInfo = productSlotsMap[item.id]
  const isOutOfStockFromSlots = productSlotInfo?.isOutOfStock
  const displayIsOutOfStock = isOutOfStockFromSlots || !slotId

  const handleQuantityChange = (newQuantity: number) => {
    if (useAddToCartDialog) {
      setAddedToCartProduct({ productId: item.id, product: item })
    } else if (newQuantity === 0 && cartItem) {
      removeFromCart.mutate(cartItem.id)
    } else if (newQuantity === 1 && !cartItem) {
      const slotId = getQuickestSlot(item.id)
      if (!slotId) {
        alert('No available delivery slot for this product')
        return
      }
      const slot = slotMap[slotId]
      const deliveryTime = slot ? dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A') : ''
      addToCart.mutate(
        { productId: item.id, quantity: 1, slotId, storeId: item.storeId },
        {
          onSuccess: () => {
            alert(`Added ${item.name} for delivery at ${deliveryTime}`)
          },
        }
      )
    } else if (cartItem) {
      updateCartItem.mutate({ productId: item.id, quantity: newQuantity })
    }
  }

  return (
    <div
      className="flex max-w-[300px] flex-col overflow-hidden rounded-2xl bg-white pb-2 border border-gray-300"
      onClick={onPress}
    >
      {/* Image Container */}
      <div className="relative aspect-square w-full overflow-hidden bg-gray-100">
        {imageUri && !imageError ? (
          <img
            src={imageUri}
            alt={item.name}
            className="h-full w-full object-cover"
            onError={() => setImageError(true)}
            onLoad={() => setImageLoading(false)}
          />
        ) : (
          <div className="flex h-full w-full items-center justify-center bg-gray-100">
            <ImageOff className="h-8 w-8 text-gray-400" />
          </div>
        )}

        {imageLoading && imageUri && !imageError && (
          <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
            <div className="h-6 w-6 animate-spin rounded-full border-2 border-brand-500 border-t-transparent" />
          </div>
        )}

        {displayIsOutOfStock && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/40">
            <div className="rounded-full bg-red-500 px-3 py-1">
              <p className="text-xs font-bold text-white">Out of Stock</p>
            </div>
          </div>
        )}

        {miniView && (
          <div className="absolute bottom-2 right-2">
            {quantity > 0 ? (
              <MiniQuantifier
                value={quantity}
                setValue={handleQuantityChange}
                step={item.incrementStep}
              />
            ) : (
              <div
                className="flex h-8 w-8 items-center justify-center rounded-full bg-white shadow-md"
                onClick={(e) => {
                  e.stopPropagation()
                  handleQuantityChange(1)
                }}
              >
                <ShoppingCart className="h-4 w-4 text-brand-500" />
              </div>
            )}
          </div>
        )}
      </div>

      {/* Content */}
      <div className="px-3 pt-3">
        <p className="font-bold mb-1 text-sm text-gray-900">
          {item.name}
        </p>

        <div className="mb-2 flex flex-row items-baseline">
          <p className="font-bold text-base text-brand-500">
            ₹{item.price}
          </p>
          {item.marketPrice && Number(item.marketPrice) > Number(item.price) && (
            <p className="ml-2 text-xs text-gray-400 line-through">
              ₹{item.marketPrice}
            </p>
          )}
        </div>

        <div className="mb-2 flex flex-row items-center">
          <p className="text-xs font-medium text-gray-500">
            Quantity:{' '}
            <span className="font-semibold text-brand-500">
              {formatQuantity(item.productQuantity || 1, item.unitNotation).display}
            </span>
          </p>
        </div>

        {showDeliveryInfo && displayDeliveryDate && (
          <div className="mb-2 flex flex-row items-center self-start rounded-lg border border-brand-100 bg-brand-50 px-2 py-1.5">
            <Truck className="h-3 w-3 text-brand-600" />
            <p className="ml-1.5 text-[10px] font-bold text-brand-700">
              {dayjs(displayDeliveryDate).format('ddd, DD MMM • h:mm A')}
            </p>
          </div>
        )}

        {!miniView && (
          <>
            {displayIsOutOfStock ? (
              <div className="mt-1 rounded-lg bg-gray-100 py-2 text-center">
                <p className="text-xs font-bold uppercase tracking-wide text-gray-400">
                  Unavailable
                </p>
              </div>
            ) : quantity > 0 ? (
              <Quantifier
                value={quantity}
                setValue={handleQuantityChange}
                step={item.incrementStep}
                unit={item.unitNotation}
              />
            ) : (
              <button
                className="mt-1 flex w-full items-center justify-center gap-1 rounded-lg bg-brand-500 py-2 hover:bg-brand-600 active:bg-brand-700"
                onClick={(e) => {
                  e.stopPropagation()
                  handleQuantityChange(1)
                }}
              >
                <ShoppingCart className="h-4 w-4 text-white" />
                <span className="text-xs font-bold uppercase tracking-wide text-white">
                  Add to Cart
                </span>
              </button>
            )}
          </>
        )}
      </div>
    </div>
  )
}
