import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useCentralProductStore } from '../lib/stores/central-product-store'
import { useAddToCart } from '../hooks/cart-query-hooks'
import { useState } from 'react'
import { p, MyButton, Quantifier, AppContainer, div } from 'web-components'
import { ShoppingCart, ArrowLeft } from 'lucide-react'

export const Route = createFileRoute('/stores/$storeId/product/$productId')({
  component: StoreProductDetailPage,
})

function StoreProductDetailPage() {
  const params = Route.useParams()
  const { productId, storeId } = params
  const pid = Number(productId)
  const navigate = useNavigate()
  const [quantity, setQuantity] = useState(1)
  const productsById = useCentralProductStore((s) => s.productsById)
  const product = productsById[pid]
  const addToCart = useAddToCart('regular')

  const handleAddToCart = () => {
    if (!product) return
    addToCart.mutate(
      { productId: product.id, quantity, storeId: product.storeId },
      { onSuccess: () => navigate({ to: '/cart' }) }
    )
  }

  if (!product) {
    return (
      <AppContainer>
        <p>Product not found</p>
      </AppContainer>
    )
  }

  const price = product.discountedPrice ?? product.price
  const imageUrl = product.images?.[0]

  return (
    <AppContainer>
      <div
        onClick={() => navigate({ to: '/stores/$storeId', params: { storeId } })}
        className="mb-4 flex items-center gap-2"
      >
        <ArrowLeft className="h-5 w-5" />
      </div>

      {imageUrl && (
        <div className="mb-4 aspect-square w-full overflow-hidden rounded-xl bg-gray-100">
          <img
            src={imageUrl}
            alt={product.name}
            className="h-full w-full object-cover"
          />
        </div>
      )}

      <p className="font-bold mb-1 text-xl">
        {product.name}
      </p>
      <p className="mb-2 text-sm text-gray-500">
        {product.unitValue}{product.unit}
      </p>

      <div className="mb-4 flex items-baseline gap-2">
        <p className="font-bold text-2xl text-brand-600">
          ₹{price}
        </p>
        {product.discountedPrice && (
          <p className="text-sm text-gray-400 line-through">
            ₹{product.price}
          </p>
        )}
      </div>

      {product.description && (
        <p className="mb-4 text-gray-600">{product.description}</p>
      )}

      <div className="mb-6">
        <Quantifier value={quantity} setValue={setQuantity} max={10} />
      </div>

      <MyButton
        fullWidth
        onClick={handleAddToCart}
        disabled={addToCart.isPending}
        className="flex items-center justify-center gap-2 bg-brand-500 text-white"
      >
        <ShoppingCart className="h-4 w-4" />
        {addToCart.isPending ? 'Adding...' : 'Add to Cart'}
      </MyButton>
    </AppContainer>
  )
}
