import { createFileRoute, useNavigate, useSearch } from '@tanstack/react-router'
import { useState, useMemo } from 'react'
import { p, div, MiniQuantifier } from 'web-components'
import { useAllProducts, useStores } from '../hooks/prominent-api-hooks'
import { useCentralProductStore } from '../lib/stores/central-product-store'
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
import { AppLayout } from '../components/AppLayout'
import { Store, Grid3X3, ChevronLeft, ShoppingCart, Zap } from 'lucide-react'

export const Route = createFileRoute('/flash')({
  component: FlashDeliveryPage,
})

function FlashDeliveryPage() {
  const navigate = useNavigate()
  const search = useSearch({ from: '/flash' }) as { storeId?: string }
  const storeId = search.storeId ? Number(search.storeId) : undefined

  const { data: storesData } = useStores()
  const { productsById } = useCentralProductStore()
  const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)

  const stores = storesData?.stores || []

  const addToCart = useAddToCart('flash')
  const { data: cartData } = useGetCart('flash')

  // Get flash products from central store
  const allFlashProducts = useMemo(() => {
    return Object.values(productsById).filter(
      (product: any) =>
        product &&
        productSlotsMap[product.id]?.isFlashAvailable &&
        !productSlotsMap[product.id]?.isOutOfStock
    )
  }, [productsById, productSlotsMap])

  // Filter by store if selected
  const filteredProducts = storeId
    ? allFlashProducts.filter((p: any) => p.storeId === storeId)
    : allFlashProducts

  const handleAddToCart = (productId: number) => {
    const item = filteredProducts.find((p: any) => p.id === productId)
    addToCart.mutate(
      { productId, quantity: 1, storeId: item?.storeId },
      {
        onSuccess: () => {
          alert(`Added ${item?.name || 'item'} for 1 Hr Delivery`)
        },
      }
    )
  }

  return (
    <AppLayout isFlashDelivery={true}>
      <div className="min-h-screen bg-gray-50">
        {/* Header - Flash Delivery Style */}
        <div className="sticky top-0 z-20 border-b border-gray-200 bg-white px-4 py-3">
          <div className="flex items-center gap-2">
            {/* Back Button */}
            <button
              onClick={() => navigate({ to: '/home' })}
              className="p-1 hover:bg-gray-100 rounded-full"
            >
              <ChevronLeft className="h-6 w-6 text-gray-700" />
            </button>

            {/* Flash Delivery Title */}
            <div className="flex items-center gap-2">
              <Zap className="h-6 w-6 text-[#f81260]" fill="#f81260" />
              <p className="text-lg font-bold text-[#f81260]">
                Delivery within 1 hour
              </p>
            </div>
          </div>
        </div>

        <div className="flex flex-row">
          {/* StoreSidebar - Fixed width on left for both mobile and desktop */}
          <div className="w-20 shrink-0 md:w-24">
            <StoreSidebar
              stores={stores}
              storeId={storeId}
              onStoreSelect={(newStoreId) =>
                navigate({
                  to: '/flash',
                  search: { storeId: newStoreId },
                })
              }
              onAllSelect={() =>
                navigate({ to: '/flash' })
              }
            />
          </div>

          {/* Products Grid */}
          <div className="flex-1 p-4">
            {/* Info Banner */}
            <div className="mb-4 rounded-xl bg-yellow-50 p-3 border border-yellow-200">
              <p className="text-sm text-yellow-800">
                Get these products delivered within 1 hour! Only available for select items.
              </p>
            </div>

            <div className="mb-4 flex items-center justify-between">
              <p className="font-bold text-xl text-gray-900">
                {storeId
                  ? stores.find((s: any) => s.id === storeId)?.name ||
                    'Store Products'
                  : 'All Products'}
              </p>
              <p className="text-sm text-gray-500">
                {filteredProducts.length} items
              </p>
            </div>

            <div className="grid grid-cols-2 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4">
              {filteredProducts.map((product: any) => (
                <CompactProductCard
                  key={product.id}
                  item={product}
                  handleAddToCart={handleAddToCart}
                  onPress={() =>
                    navigate({
                      to: '/flash/product/$id',
                      params: { id: String(product.id) },
                    })
                  }
                />
              ))}
            </div>

            {filteredProducts.length === 0 && (
              <div className="py-10 text-center">
                <p className="font-medium text-gray-400">
                  {storeId
                    ? 'No flash delivery products from this store.'
                    : 'No flash delivery products available.'}
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </AppLayout>
  )
}

interface StoreSidebarProps {
  stores: any[];
  storeId?: number;
  onStoreSelect: (storeId: number) => void;
  onAllSelect: () => void;
}

function StoreSidebar({
  stores,
  storeId,
  onStoreSelect,
  onAllSelect,
}: StoreSidebarProps) {
  return (
    <div className="sticky top-[73px] z-10 h-[calc(100vh-73px)] w-full overflow-y-auto border-r border-gray-200 bg-white p-2 md:top-0 md:h-auto md:p-3">
      <div className="flex flex-col gap-2 md:gap-3">
        {/* All Products Item */}
        <div
          onClick={onAllSelect}
          className={`flex flex-col items-center rounded-2xl p-2 md:p-3 ${
            !storeId
              ? 'bg-gradient-to-br from-[#f81260] to-[#d10f4f] text-white shadow-lg'
              : 'border border-gray-100 bg-white text-gray-500'
          }`}
        >
          <div
            className={`mb-1 flex h-8 w-8 items-center justify-center rounded-full border md:h-10 md:w-10 ${
              !storeId ? 'border-white/30 bg-white/20' : 'bg-gray-50'
            }`}
          >
            <Grid3X3
              className={`h-4 w-4 md:h-5 md:w-5 ${!storeId ? 'text-white' : 'text-gray-500'}`}
            />
          </div>
          <p
            className={`text-center text-[10px] font-bold ${!storeId ? 'text-white' : 'text-gray-500'}`}
          >
            ALL
          </p>
        </div>

        <div className="h-px bg-gray-200 my-1" />

        {/* Store Items */}
        {stores.map((store: any) => {
          const isActive = storeId === store.id;

          return (
            <div
              key={store.id}
              onClick={() => onStoreSelect(store.id)}
              className={`flex flex-col items-center rounded-2xl p-2 ${
                isActive
                  ? 'bg-gradient-to-br from-[#f81260] to-[#d10f4f] text-white shadow-lg'
                  : 'border border-gray-100 bg-white text-gray-500'
              }`}
            >
              <div
                className={`mb-1 md:mb-2 flex h-10 w-10 items-center justify-center overflow-hidden rounded-full border-2 md:h-12 md:w-12 ${
                  isActive
                    ? 'border-white bg-white'
                    : 'border-gray-100 bg-gray-50'
                }`}
              >
                {store.signedImageUrl ? (
                  <img
                    src={store.signedImageUrl}
                    alt={store.name}
                    className="h-full w-full object-cover"
                  />
                ) : (
                  <Store
                    className={`h-5 w-5 md:h-6 md:w-6 ${isActive ? 'text-[#f81260]' : 'text-gray-400'}`}
                  />
                )}
              </div>
              <p
                className={`w-full text-center text-[10px] leading-tight ${
                  isActive
                    ? 'font-bold text-white'
                    : 'font-medium text-gray-500'
                }`}
              >
                {store.name.replace(/^The\s+/i, '')}
              </p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

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}` };
};

interface CompactProductCardProps {
  item: any;
  handleAddToCart: (productId: number) => void;
  onPress?: () => void;
}

function CompactProductCard({
  item,
  handleAddToCart,
  onPress,
}: CompactProductCardProps) {
  const { data: cartData } = useGetCart('flash');
  const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap);
  const updateCartItem = useUpdateCartItem('flash');
  const removeFromCart = useRemoveFromCart('flash');

  const cartItem = cartData?.items?.find(
    (cartItem: any) => cartItem.productId === item.id,
  );
  const quantity = cartItem?.quantity || 0;
  const isOutOfStock = productSlotsMap[item.id]?.isOutOfStock;

  const handleQuantityChange = (newQuantity: number) => {
    if (newQuantity === 0 && cartItem) {
      removeFromCart.mutate(cartItem.id);
    } else if (newQuantity === 1 && !cartItem) {
      handleAddToCart(item.id);
    } else if (cartItem) {
      updateCartItem.mutate({ productId: cartItem.id, quantity: newQuantity });
    }
  };

  const price = item.flashPrice ?? item.price

  return (
    <div
      onClick={onPress}
      className="mb-2 overflow-hidden rounded-lg border border-gray-100 bg-white shadow-sm"
    >
      <div className="relative">
        <img
          src={item.images?.[0]}
          alt={item.name}
          className="aspect-square w-full object-cover"
        />
        {isOutOfStock && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/30">
            <p className="text-xs font-bold text-white">Out of Stock</p>
          </div>
        )}
        <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-[#f81260]" />
            </div>
          )}
        </div>
      </div>

      <div className="p-2">
        <p className="font-medium mb-1 text-xs text-gray-900">{item.name}</p>

        <div className="flex items-center justify-between">
          <div className="flex flex-wrap items-baseline">
            <p className="font-bold text-sm text-[#f81260]">₹{price}</p>
            {item.marketPrice && Number(item.marketPrice) > Number(item.price) && (
              <p className="ml-1 text-xs text-gray-400 line-through">
                ₹{item.marketPrice}
              </p>
            )}
            <p className="ml-1 text-xs text-gray-600">
              Qty:{" "}
              <span className="font-semibold text-[#f81260]">
                {formatQuantity(item.productQuantity || 1, item.unit || item.unitNotation).display}
              </span>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}