import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
import { useState, useMemo, useEffect } from 'react'
import { p, div, MiniQuantifier, AppContainer } from 'web-components'
import { useCentralProductStore } from '../lib/stores/central-product-store'
import { useCentralSlotStore } from '../lib/stores/central-slot-store'
import { trpc } from '../lib/trpc-client'
import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
import { useSlots } from '../hooks/prominent-api-hooks'
import { useCartStore } from '../lib/stores/cart-store'
import { useProductSlotIdentifier } from '../hooks/useProductSlotIdentifier'
import dayjs from 'dayjs'
import { ChevronLeft, Star, Zap, Truck, Store, Package, Plus, Clock, AlertCircle } from 'lucide-react'
import { Dialog } from '../components/Dialog'
import { FloatingCartBar } from '../components/FloatingCartBar'
import { AppLayout } from '../components/AppLayout'

export const Route = createFileRoute('/home/product/$id')({
  component: ProductDetailPage,
})

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

function ProductDetailPage() {
  const { id } = useParams({ from: '/home/product/$id' })
  const productId = Number(id)
  const navigate = useNavigate()
  const [showAllSlots, setShowAllSlots] = useState(false)
  const [currentImageIndex, setCurrentImageIndex] = useState(0)
  
  const { data: productDetail, isLoading, error, refetch } = trpc.user.product.getProductDetails.useQuery(
    { id: String(productId) },
    { enabled: !!productId }
  )
  const { data: slotsData } = useSlots()
  const { data: cartData } = useGetCart('regular')
  const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap)
  const { getQuickestSlot } = useProductSlotIdentifier()
  const { setAddedToCartProduct } = useCartStore()
  const addToCart = useAddToCart('regular')
  const addToFlashCart = useAddToCart('flash')
  const updateCartItem = useUpdateCartItem('regular')
  const removeFromCart = useRemoveFromCart('regular')

  const productAvailability = useMemo(() => {
    if (!productDetail) return null
    return productSlotsMap[productDetail.id]
  }, [productDetail, productSlotsMap])

  const sortedDeliverySlots = useMemo(() => {
    if (!slotsData?.slots || !productDetail) return []
    
    const productSlots = slotsData.slots.filter((slot: any) =>
      slot.products?.some((p: any) => p.id === productDetail.id)
    )
    
    return productSlots.sort((a: any, b: any) => {
      const deliveryDiff = new Date(a.deliveryTime).getTime() - new Date(b.deliveryTime).getTime()
      if (deliveryDiff !== 0) return deliveryDiff
      return new Date(a.freezeTime).getTime() - new Date(b.freezeTime).getTime()
    })
  }, [slotsData, productDetail])

  const cartItem = productDetail 
    ? cartData?.items?.find((item: any) => item.productId === productDetail.id)
    : null
  const quantity = cartItem?.quantity || 0

  const discountPercentage = productDetail?.marketPrice
    ? Math.round(((Number(productDetail.marketPrice) - Number(productDetail.price)) / Number(productDetail.marketPrice)) * 100)
    : 0

  const handleQuantityChange = (newQuantity: number) => {
    if (!productDetail) return

    if (newQuantity === 0 && cartItem) {
      removeFromCart.mutate(cartItem.id)
    } else if (newQuantity === 1 && !cartItem) {
      handleAddToCart()
    } else if (cartItem) {
      updateCartItem.mutate({ productId: cartItem.id, quantity: newQuantity })
    }
  }

  const handleAddToCart = () => {
    if (!productDetail) return
    const slotId = getQuickestSlot(productDetail.id)
    if (!slotId) {
      alert('No available delivery slot for this product')
      return
    }
    addToCart.mutate(
      { productId: productDetail.id, quantity: 1, slotId, storeId: productDetail.storeId },
      {
        onSuccess: () => {
          const slot = slotsData?.slots?.find((s: any) => s.id === slotId)
          const deliveryTime = slot?.deliveryTime
            ? dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A')
            : ''
          alert(`Added ${productDetail.name} for delivery at ${deliveryTime}`)
        },
      }
    )
  }

  const handleBuyNow = () => {
    if (!productDetail) return
    addToFlashCart.mutate(
      { productId: productDetail.id, quantity: 1, storeId: productDetail.storeId },
      {
        onSuccess: () => {
          navigate({ to: '/flash/cart' })
        },
      }
    )
  }

  const handleSlotAddToCart = (selectedSlotId: number) => {
    if (!productDetail) return
    
    if (cartItem) {
      removeFromCart.mutate(
        { itemId: cartItem.id },
        {
          onSuccess: () => {
            addToCart.mutate(
              { productId: productDetail.id, quantity: cartItem.quantity + 1, slotId: selectedSlotId, storeId: productDetail.storeId }
            )
          },
        }
      )
    } else {
      addToCart.mutate(
        { productId: productDetail.id, quantity: 1, slotId: selectedSlotId, storeId: productDetail.storeId }
      )
    }
    setShowAllSlots(false)
  }

  if (isLoading) {
    return (
      <AppLayout>
        <div className="flex min-h-screen items-center justify-center">
          <p className="text-gray-500">Loading product details...</p>
        </div>
      </AppLayout>
    )
  }

  if (error || !productDetail) {
    return (
      <AppLayout>
        <div className="flex min-h-screen flex-col items-center justify-center">
          <AlertCircle className="h-12 w-12 text-red-500" />
          <p className="mt-4 text-lg font-bold text-gray-900">Oops!</p>
          <p className="text-gray-500">Product not found or error loading</p>
        </div>
      </AppLayout>
    )
  }

  const images = productDetail.images || []

  return (
    <AppLayout>
      <div className="min-h-screen bg-gray-50 pb-20">
        {/* Back Button */}
        <div className="fixed left-4 top-4 z-30">
          <button
            onClick={() => navigate({ to: '/home' })}
            className="flex h-10 w-10 items-center justify-center rounded-full bg-white/90 shadow-md backdrop-blur-sm"
          >
            <ChevronLeft className="h-6 w-6 text-gray-700" />
          </button>
        </div>

        {/* Image Carousel */}
        <div className="relative bg-white shadow-sm">
          <div className="aspect-square w-full overflow-hidden">
            {images.length > 0 ? (
              <img
                src={images[currentImageIndex]}
                alt={productDetail.name}
                className="h-full w-full object-cover"
              />
            ) : (
              <div className="flex h-full w-full items-center justify-center bg-gray-100">
                <Package className="h-20 w-20 text-gray-300" />
              </div>
            )}
          </div>
          
          {/* Image Pagination Dots */}
          {images.length > 1 && (
            <div className="absolute bottom-4 left-1/2 flex -translate-x-1/2 gap-2">
              {images.map((_, idx) => (
                <button
                  key={idx}
                  onClick={() => setCurrentImageIndex(idx)}
                  className={`h-2 rounded-full transition-all ${
                    idx === currentImageIndex ? 'w-6 bg-brand-500' : 'w-2 bg-gray-300'
                  }`}
                />
              ))}
            </div>
          )}
        </div>

        <div className="px-4 py-4">
          {/* Product Info Card */}
          <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
            <div className="mb-2 flex items-start justify-between">
              <h1 className="flex-1 text-2xl font-bold text-gray-900">{productDetail.name}</h1>
              <div className="flex gap-2">
                {productAvailability?.isFlashAvailable && (
                  <div className="flex items-center gap-1 rounded-full bg-pink-100 px-3 py-1">
                    <Zap className="h-3 w-3 text-pink-600" fill="#EC4899" />
                    <span className="text-xs font-bold text-pink-700">1 Hr Delivery</span>
                  </div>
                )}
                {productAvailability?.isOutOfStock && (
                  <div className="rounded-full bg-red-100 px-3 py-1">
                    <span className="text-xs font-bold text-red-700">Out of Stock</span>
                  </div>
                )}
              </div>
            </div>

            <p className="mb-4 text-base leading-6 text-gray-500">{productDetail.shortDescription}</p>

            {/* Price Section */}
            <div className="mb-4">
              <div className="flex items-end">
                <span className="text-3xl font-bold text-gray-900">₹{productDetail.price}</span>
                <span className="mb-1 ml-1 text-lg text-gray-500">
                  / {formatQuantity(productDetail.productQuantity || 1, productDetail.unitNotation)}
                </span>
                
                {productDetail.marketPrice && (
                  <div className="mb-1 ml-3 flex items-center">
                    <span className="mr-2 text-base text-gray-400 line-through">₹{productDetail.marketPrice}</span>
                    <span className="rounded bg-green-100 px-2 py-0.5 text-xs font-bold text-green-700">
                      {discountPercentage}% OFF
                    </span>
                  </div>
                )}
              </div>

              {/* Flash Price */}
              {productAvailability?.isFlashAvailable && productDetail.flashPrice && productDetail.flashPrice !== productDetail.price && (
                <div className="mt-1">
                  <span className="text-lg font-bold text-pink-600">
                    1 Hr Delivery: ₹{productDetail.flashPrice} / {formatQuantity(productDetail.productQuantity || 1, productDetail.unitNotation)}
                  </span>
                </div>
              )}
            </div>

            {/* Action Buttons */}
            <div className="flex gap-3">
              {quantity > 0 ? (
                <div className="flex-1">
                  <MiniQuantifier
                    value={quantity}
                    setValue={handleQuantityChange}
                    step={productDetail.incrementStep || 1}
                    unit={productDetail.unitNotation}
                  />
                </div>
              ) : (
                <button
                  onClick={() => {
                    if (productAvailability?.isOutOfStock) return
                    setAddedToCartProduct({ productId: productDetail.id, product: productDetail })
                  }}
                  disabled={productAvailability?.isOutOfStock}
                  className={`flex-1 rounded-xl border py-3.5 font-bold transition-colors ${
                    productAvailability?.isOutOfStock
                      ? 'border-gray-300 text-gray-400'
                      : 'border-brand-500 text-brand-500 hover:bg-brand-50'
                  }`}
                >
                  {productAvailability?.isOutOfStock ? 'Unavailable' : 'Add to Cart'}
                </button>
              )}

              {productAvailability?.isFlashAvailable ? (
                <button
                  onClick={handleBuyNow}
                  disabled={productAvailability?.isOutOfStock}
                  className={`flex-1 rounded-xl py-3.5 font-bold shadow-md transition-colors ${
                    productAvailability?.isOutOfStock
                      ? 'bg-gray-300 text-gray-500'
                      : 'bg-pink-50 text-pink-600 hover:bg-pink-100'
                  }`}
                >
                  {productAvailability?.isOutOfStock ? 'Out of Stock' : 'Get in 1 Hour'}
                </button>
              ) : (
                <div className="flex-1" />
              )}
            </div>
          </div>

          {/* Delivery Slots */}
          <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
            <div className="mb-4 flex items-center">
              <div className="mr-3 flex h-8 w-8 items-center justify-center rounded-full bg-blue-50">
                <Truck className="h-4 w-4 text-blue-500" />
              </div>
              <h2 className="text-lg font-bold text-gray-900">Available Slots</h2>
            </div>

            {sortedDeliverySlots.length === 0 ? (
              <p className="italic text-gray-400">No delivery slots available currently</p>
            ) : (
              <>
                {sortedDeliverySlots.slice(0, 2).map((slot: any, index: number) => (
                  <button
                    key={index}
                    onClick={() => handleSlotAddToCart(slot.id)}
                    disabled={productAvailability?.isOutOfStock}
                    className="mb-3 flex w-full items-start rounded-xl border border-gray-100 bg-gray-50 p-3 text-left transition-colors hover:bg-gray-100"
                  >
                    <Truck className="mt-0.5 h-5 w-5 text-blue-500" />
                    <div className="ml-3 flex-1">
                      <p className="text-sm font-bold text-gray-900">
                        {dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A')}
                      </p>
                      <p className="mt-1 text-xs text-gray-500">
                        Orders Close: {dayjs(slot.freezeTime).format('h:mm A')}
                      </p>
                    </div>
                    <Plus className="mt-0.5 h-5 w-5 text-blue-500" />
                  </button>
                ))}
                {sortedDeliverySlots.length > 2 && (
                  <button
                    onClick={() => setShowAllSlots(true)}
                    className="w-full py-2 text-center text-sm font-bold text-brand-500"
                  >
                    View All {sortedDeliverySlots.length} Slots
                  </button>
                )}
              </>
            )}
          </div>

          {/* Description */}
          <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
            <h2 className="mb-3 text-lg font-bold text-gray-900">About the Product</h2>
            {!productDetail.longDescription ? (
              <p className="italic text-gray-400">No detailed description available.</p>
            ) : (
              <p className="leading-6 text-gray-600">{productDetail.longDescription}</p>
            )}

            {productDetail.store && (
              <div className="mt-6 flex items-center border-t border-gray-100 pt-4">
                <div className="mr-3 flex h-10 w-10 items-center justify-center rounded-full bg-gray-100">
                  <Store className="h-5 w-5 text-gray-600" />
                </div>
                <div>
                  <p className="text-xs font-bold uppercase text-gray-500">Sourced From</p>
                  <p className="font-bold text-gray-900">{productDetail.store.name}</p>
                </div>
              </div>
            )}
          </div>

          {/* Package Deals */}
          {productDetail.specialDeals && productDetail.specialDeals.length > 0 && (
            <div className="mb-4 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
              <div className="mb-4 flex items-center">
                <div className="mr-3 flex h-8 w-8 items-center justify-center rounded-full bg-amber-50">
                  <Package className="h-4 w-4 text-amber-500" />
                </div>
                <h2 className="text-lg font-bold text-gray-900">Bulk Savings</h2>
              </div>

              {productDetail.specialDeals.map((deal: any, index: number) => (
                <div
                  key={index}
                  className="mb-2 flex items-center justify-between rounded-xl border border-amber-100 bg-amber-50 p-3"
                >
                  <span className="font-medium text-amber-900">
                    Buy {deal.quantity} {formatQuantity(parseFloat(deal.quantity), productDetail.unitNotation)}
                  </span>
                  <span className="text-lg font-bold text-amber-900">₹{deal.price}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* All Slots Dialog */}
        <Dialog open={showAllSlots} onClose={() => setShowAllSlots(false)} title="All Delivery Slots">
          <div className="max-h-[60vh] overflow-y-auto p-4">
            {sortedDeliverySlots.map((slot: any, index: number) => (
              <button
                key={index}
                onClick={() => handleSlotAddToCart(slot.id)}
                disabled={productAvailability?.isOutOfStock}
                className="mb-3 flex w-full items-start rounded-xl border border-gray-100 bg-gray-50 p-4 text-left transition-colors hover:bg-gray-100"
              >
                <Truck className="mt-0.5 h-5 w-5 text-blue-500" />
                <div className="ml-3 flex-1">
                  <p className="text-base font-bold text-gray-900">
                    {dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A')}
                  </p>
                  <p className="mt-1 text-sm text-gray-500">
                    Orders Close: {dayjs(slot.freezeTime).format('h:mm A')}
                  </p>
                </div>
                <Plus className="mt-0.5 h-6 w-6 text-blue-500" />
              </button>
            ))}
          </div>
          <div className="border-t border-gray-100 p-4">
            <button
              onClick={() => setShowAllSlots(false)}
              className="w-full rounded-xl bg-gray-900 py-3.5 font-bold text-white"
            >
              Close
            </button>
          </div>
        </Dialog>

        {/* Floating Cart Bar */}
        <FloatingCartBar />
      </div>
    </AppLayout>
  )
}