import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks'
import { useAllProducts } from '../hooks/prominent-api-hooks'
import { p, MyButton, Quantifier, AppContainer, div } from 'web-components'
import { Trash2 } from 'lucide-react'

export const Route = createFileRoute('/cart')({ component: CartPage })

function CartPage() {
  const navigate = useNavigate()
  const { data: cart } = useGetCart('regular')
  const { data: productsData } = useAllProducts()
  const updateItem = useUpdateCartItem('regular')
  const removeItem = useRemoveFromCart('regular')

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

  const cartItems = (cart?.items || []).filter((item) => productsById[item.productId])

  let total = 0
  cartItems.forEach((item) => {
    const product = productsById[item.productId]
    if (product) {
      total += product.price * item.quantity
    }
  })

  return (
    <AppContainer>
      <p className="font-bold mb-4 text-xl">
        Your Cart
      </p>

      {cartItems.length === 0 ? (
        <div className="flex flex-col items-center gap-4 py-20">
          <p className="text-gray-500">Your cart is empty</p>
          <MyButton
            textContent="Browse Products"
            onClick={() => navigate({ to: '/home' })}
          />
        </div>
      ) : (
        <>
          <div className="flex flex-col gap-3">
            {cartItems.map((item) => {
              const product = productsById[item.productId]
              const price = product.price
              return (
                <div
                  key={item.productId}
                  className="flex items-center gap-3 rounded-xl border border-gray-100 bg-white p-3 shadow-sm"
                >
                  <img
                    src={product.images?.[0]}
                    alt={product.name}
                    className="h-16 w-16 rounded-lg object-cover"
                  />
                  <div className="flex-1">
                    <p className="font-semibold text-sm">
                      {product.name}
                    </p>
                    <p className="text-brand-600 text-sm font-bold">
                      ₹{price}
                    </p>
                    <Quantifier
                      value={item.quantity}
                      setValue={(q) => updateItem.mutate({ productId: item.productId, quantity: q })}
                    />
                  </div>
                  <div onClick={() => removeItem.mutate(item.productId)}>
                    <Trash2 className="h-5 w-5 text-red-500" />
                  </div>
                </div>
              )
            })}
          </div>

          <div className="fixed bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4 shadow-lg">
            <div className="mb-3 flex items-center justify-between">
              <p className="font-bold">Total</p>
              <p className="font-bold text-lg text-brand-600">
                ₹{total}
              </p>
            </div>
            <MyButton
              fullWidth
              textContent="Proceed to Checkout"
              onClick={() => navigate({ to: '/checkout' })}
              className="bg-brand-500 text-white"
            />
          </div>
        </>
      )}
    </AppContainer>
  )
}
