import React, { useState, useEffect, useMemo } from 'react'
import { useNavigate, useLocation } from '@tanstack/react-router'
import { useGetCart, useUpdateCartItem, useRemoveFromCart, useAddToCart } from '../hooks/cart-query-hooks'
import { useAllProducts } from '../hooks/prominent-api-hooks'
import { useGetEssentialConsts } from '../hooks/prominent-api-hooks'
import { p, div, MiniQuantifier } from 'web-components'
import { Dialog } from './Dialog'
import { ShoppingCart, ChevronRight, Package, X, Clock, MapPin, Home, Store, Zap, RotateCcw, User } from 'lucide-react'
import dayjs from 'dayjs'

interface FloatingCartBarProps {
  isFlashDelivery?: boolean
}

// Smart time window formatting function
const formatTimeRange = (deliveryTime: string | Date) => {
  const time = dayjs(deliveryTime)
  const endTime = time.add(1, 'hour')
  const startPeriod = time.format('A')
  const endPeriod = endTime.format('A')

  let timeRange
  if (startPeriod === endPeriod) {
    timeRange = `${time.format('h')}-${endTime.format('h')} ${startPeriod}`
  } else {
    timeRange = `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`
  }

  return `${time.format('ddd, DD MMM ')}${timeRange}`
}

export function FloatingCartBar({ isFlashDelivery = false }: FloatingCartBarProps) {
  const navigate = useNavigate()
  const [isExpanded, setIsExpanded] = useState(false)
  const [quantities, setQuantities] = useState<Record<number, number>>({})
  const cartType = isFlashDelivery ? 'flash' : 'regular'

  const { data: cartData, refetch: refetchCart } = useGetCart(cartType)
  const { data: constsData } = useGetEssentialConsts()
  const { data: productsData } = useAllProducts()
  const updateCartItem = useUpdateCartItem(cartType)
  const removeFromCart = useRemoveFromCart(cartType)
  const addToCartHook = useAddToCart(cartType)

  const products = productsData?.products || []
  const productsById: Record<number, any> = {}
  products.forEach((p: any) => { productsById[p.id] = p })

  const cartItems = cartData?.items || []
  const itemCount = cartItems.length

  useEffect(() => {
    const initial: Record<number, number> = {}
    cartItems.forEach((item) => {
      initial[item.id] = item.quantity
    })
    setQuantities(initial)
  }, [cartData])

  // Calculate total cart value
  const totalCartValue = cartItems.reduce(
    (sum, item) => {
      const product = productsById[item.productId]
      const basePrice = product?.price ?? 0
      const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice
      return sum + price * item.quantity
    },
    0
  )

  const freeDeliveryThreshold = isFlashDelivery
    ? constsData?.flashFreeDeliveryThreshold
    : constsData?.freeDeliveryThreshold
  const remainingForFreeDelivery = Math.max(0, freeDeliveryThreshold - totalCartValue)

  const cartBarColor = isFlashDelivery ? '#f81260' : 'var(--brand-600, #2563eb)'
  const cartBarBorderColor = isFlashDelivery ? '#e11d48' : 'var(--brand-500, #3b82f6)'

  return (
    <>
      {/* Collapsed Bar */}
      <div
        className="fixed bottom-18 left-4 right-4 z-40 rounded-lg border shadow-2xl"
        style={{
          backgroundColor: cartBarColor,
          borderColor: cartBarBorderColor,
          borderWidth: 1,
        }}
      >
        <div
          className="flex flex-row items-center justify-between py-3"
          onClick={() => itemCount > 0 && setIsExpanded(true)}
        >
          <div className="flex flex-1 flex-row items-center px-2">
            <div className="flex-1">
              <div className="flex flex-row items-center">
                <p className="font-bold mr-2 text-sm text-white">
                  {itemCount === 0 ? (
                    isFlashDelivery ? 'No Flash Items' : 'No Items In Cart'
                  ) : (
                    <>
                      <span className="text-base font-black text-white">
                        ₹{totalCartValue}
                      </span>
                      <span className="text-sm font-bold text-white">
                        {' '}&bull; {itemCount} {itemCount === 1 ? 'Item' : 'Items'}
                      </span>
                    </>
                  )}
                </p>
                {itemCount > 0 && <span className="text-white">▲</span>}
              </div>

              {remainingForFreeDelivery > 0 ? (
                <p className="mt-1 text-[10px] font-bold text-white/80">
                  ₹{remainingForFreeDelivery} more for <span className="text-emerald-300">FREE Delivery</span>
                </p>
              ) : itemCount > 0 ? (
                <div className="mt-0.5 flex flex-row items-center">
                  <span className="text-emerald-400">✓</span>
                  <p className="ml-1 text-[10px] font-black uppercase tracking-tighter text-emerald-300">
                    Free Delivery Unlocked
                  </p>
                </div>
              ) : (
                <p className="mt-0.5 text-[10px] text-white/60">
                  Shop for ₹{freeDeliveryThreshold}+ for free shipping
                </p>
              )}
            </div>
          </div>

          <div
            className="rounded-2xl bg-white px-3 py-2 shadow-lg mr-2"
            onClick={(e) => {
              e.stopPropagation()
              navigate({
                to: isFlashDelivery ? '/flash/cart' : '/cart',
              })
            }}
          >
            <p className="font-bold text-sm" style={{ color: cartBarColor }}>
              Go to Cart
            </p>
          </div>
        </div>
      </div>

      {/* Expanded Dialog */}
      <Dialog open={isExpanded} onClose={() => setIsExpanded(false)} title="">
        <div className="flex max-h-[80vh] flex-col">
          {/* Header */}
          <div className="flex flex-row items-center justify-between border-b border-slate-100 px-6 py-5">
            <div>
              <p className="font-bold text-xl tracking-tight text-slate-900">
                Your Cart
              </p>
              <p className="text-xs font-bold uppercase tracking-widest text-slate-400">
                {itemCount} Items
              </p>
            </div>
            <div
              className="flex h-10 w-10 items-center justify-center rounded-2xl bg-slate-100"
              onClick={() => setIsExpanded(false)}
            >
              <X className="h-6 w-6 text-slate-500" />
            </div>
          </div>

          {/* Progress Bar Header */}
          {remainingForFreeDelivery > 0 && (
            <div className="flex flex-row items-center justify-between bg-emerald-50/50 px-6 py-3">
              <div className="mr-4 flex-1">
                <div className="mb-1.5 flex flex-row items-center justify-between">
                  <p className="text-[10px] font-black uppercase text-emerald-700">Free Delivery Progress</p>
                  <p className="text-[10px] font-black text-emerald-700">
                    {Math.round((totalCartValue / freeDeliveryThreshold) * 100)}%
                  </p>
                </div>
                <div className="h-1.5 overflow-hidden rounded-full border border-emerald-100 bg-white">
                  <div
                    className="h-full bg-emerald-500"
                    style={{ width: `${(totalCartValue / freeDeliveryThreshold) * 100}%` }}
                  />
                </div>
              </div>
              <div className="items-end">
                <p className="text-[10px] font-bold text-slate-500">Needed</p>
                <p className="text-sm font-black text-emerald-600">+₹{remainingForFreeDelivery}</p>
              </div>
            </div>
          )}

          {/* Items List */}
          <div className="flex-1 overflow-y-auto px-6 py-4">
            {cartItems.map((item, index) => (
              <React.Fragment key={item.id}>
                <div className="py-4">
                  <div className="flex flex-row items-center">
                    <img
                      src={productsById[item.productId]?.images?.[0]}
                      alt=""
                      className="h-8 w-8 rounded-lg border border-slate-100 bg-slate-50 object-cover"
                    />

                    <div className="ml-4 flex-1">
                      <div className="mb-1 flex flex-row items-center justify-between">
                        <p className="font-bold flex-1 text-sm text-slate-900">
                          {productsById[item.productId]?.name || ''}{' '}
                          <span className="text-xs font-medium text-slate-500">
                            ({productsById[item.productId]?.productQuantity || 0}
                            {productsById[item.productId]?.unitNotation || ''})
                          </span>
                        </p>
                        <MiniQuantifier
                          value={quantities[item.id] || item.quantity}
                          setValue={(value) => {
                            if (value === 0) {
                              removeFromCart.mutate(item.id)
                            } else {
                              setQuantities((prev) => ({ ...prev, [item.id]: value }))
                              updateCartItem.mutate({ productId: item.id, quantity: value })
                            }
                          }}
                          step={productsById[item.productId]?.incrementStep || 1}
                        />
                      </div>
                      <div className="flex flex-row items-center justify-between">
                        {item.slotId && (
                          <div className="flex flex-row items-center rounded-lg border border-blue-100 bg-blue-50 px-2 py-1">
                            <Clock className="h-3 w-3 text-blue-600" />
                            <p className="ml-1 text-[9px] font-black uppercase text-blue-700">
                              {formatTimeRange(item.deliveryDate || new Date())}
                            </p>
                          </div>
                        )}
                        <p className="font-bold text-sm text-slate-900">
                          ₹{(() => {
                            const product = productsById[item.productId]
                            const basePrice = product?.price ?? 0
                            const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice
                            return price * item.quantity
                          })()}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
                {index < cartItems.length - 1 && <div className="h-px w-full bg-slate-200" />}
              </React.Fragment>
            ))}
          </div>

          {/* Footer */}
          <div className="border-t border-slate-100 bg-white p-6">
            <div className="mb-5 flex flex-row items-center justify-between">
              <div>
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-400">Subtotal</p>
                <p className="font-bold text-2xl text-slate-900">
                  ₹{totalCartValue}
                </p>
              </div>
              {remainingForFreeDelivery === 0 && (
                <div className="flex flex-row items-center rounded-xl border border-emerald-100 bg-emerald-50 px-3 py-1.5">
                  <Package className="h-4 w-4 text-emerald-600" />
                  <p className="ml-1.5 text-[10px] font-black uppercase text-emerald-700">Free Delivery</p>
                </div>
              )}
            </div>

            <div
              onClick={() => {
                setIsExpanded(false)
                navigate({
                  to: isFlashDelivery ? '/flash/cart' : '/cart',
                })
              }}
              className="flex flex-row items-center justify-center rounded-2xl py-4 shadow-lg"
              style={{
                background: isFlashDelivery
                  ? 'linear-gradient(90deg, #f81260, #c40e50)'
                  : 'linear-gradient(90deg, #1570EF, #194185)',
              }}
            >
              <p className="font-bold text-base uppercase tracking-widest text-white">
                Go to cart
              </p>
              <ChevronRight className="ml-1 h-5 w-5 text-white" />
            </div>
          </div>
        </div>
      </Dialog>
    </>
  )
}
