import { createFileRoute, useNavigate } from '@tanstack/react-router' import { useState } from 'react' import { useAuth } from '../lib/auth-context' import { useGetCart } from '../hooks/cart-query-hooks' import { useCentralProductStore } from '../lib/stores/central-product-store' import { trpc } from '../lib/trpc-client' import { clearLocalCart } from '../hooks/cart-query-hooks' import { p, MyButton, LoadingDialog, AppContainer, div } from 'web-components' import { useQueryClient } from '@tanstack/react-query' export const Route = createFileRoute('/home/checkout')({ component: CheckoutPage }) function CheckoutPage() { const navigate = useNavigate() const queryClient = useQueryClient() const { isAuthenticated } = useAuth() const { data: cart } = useGetCart('regular') const productsById = useCentralProductStore((s) => s.productsById) const [isLoading, setIsLoading] = useState(false) const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(undefined, { enabled: isAuthenticated, }) const [selectedAddressId, setSelectedAddressId] = useState(null) const placeOrderMutation = trpc.user.order.placeOrder.useMutation({ onSuccess: (data) => { const order = data.data?.[0] clearLocalCart('regular') queryClient.invalidateQueries({ queryKey: ['local-cart-regular'] }) navigate({ to: '/home/order-success', search: { orderId: order?.id, totalAmount: total }, }) }, onSettled: () => setIsLoading(false), }) const cartItems = (cart?.items || []).filter((item) => productsById[item.productId]) let total = 0 cartItems.forEach((item) => { const product = productsById[item.productId] if (product) { total += (product.discountedPrice ?? product.price) * item.quantity } }) const handlePlaceOrder = () => { if (!selectedAddressId) return setIsLoading(true) placeOrderMutation.mutate({ selectedItems: cartItems.map((item) => ({ productId: item.productId, quantity: item.quantity, slotId: null, })), addressId: selectedAddressId, paymentMethod: 'cod', isFlashDelivery: false, }) } return (

Checkout

{/* Address Selection */}

Delivery Address

{addresses?.data?.map((addr: any) => (
setSelectedAddressId(addr.id)} className={`mb-2 rounded-xl border p-3 ${ selectedAddressId === addr.id ? 'border-brand-500 bg-brand-50' : 'border-gray-200' }`} >

{addr.name}

{addr.addressLine1}, {addr.city}

{addr.phone}

))}
{/* Order Summary */}

Order Summary

{cartItems.map((item) => { const product = productsById[item.productId] if (!product) return null return (

{product.name} x{item.quantity}

₹{(product.discountedPrice ?? product.price) * item.quantity}

) })}

Total

₹{total}

) }