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 { useRegionStore } from '../lib/stores/region-store' import { confirmRegionSwitch } from '../lib/region-switch' 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 { data: regions } = trpc.common.listRegions.useQuery() const selectedRegionId = useRegionStore((state) => state.selectedRegionId) 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: String(order?.id), totalAmount: String(total) }, }) }, onError: (error: any) => { const message = typeof error?.message === 'string' && error.message.length > 0 ? error.message : 'Failed to place order' alert(message) }, onSettled: () => setIsLoading(false), }) const cartItems = (cart?.items || []).filter((item) => productsById[item.skuId]) let total = 0 cartItems.forEach((item) => { const product = productsById[item.skuId] if (product) { total += product.price * item.quantity } }) const handleAddressPress = (addr: any) => { // Cross-region addresses switch the browsing region (clearing the cart). if (selectedRegionId && addr.regionId && addr.regionId !== selectedRegionId) { const targetRegion = (regions ?? []).find((region) => region.id === addr.regionId) if (!targetRegion) { alert('This address belongs to a region that is not currently available.') return } const ok = window.confirm( `This address is in ${targetRegion.name}. Switching will clear your entire cart and take you home. Continue?` ) if (!ok) return setIsLoading(true) void (async () => { try { await confirmRegionSwitch(targetRegion, queryClient) navigate({ to: '/home' }) } finally { setIsLoading(false) } })() return } setSelectedAddressId(addr.id) } const handlePlaceOrder = () => { if (!selectedAddressId) return if (!selectedRegionId) { alert('Please select a delivery region before placing an order') return } setIsLoading(true) placeOrderMutation.mutate({ selectedItems: cartItems.map((item) => ({ skuId: item.skuId, quantity: item.quantity, slotId: item.slotId ?? null, })), addressId: selectedAddressId, regionId: selectedRegionId, isFlashDelivery: false, }) } return (

Checkout

{/* Address Selection */}

Delivery Address

{addresses?.data?.map((addr: any) => (
handleAddressPress(addr)} 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.skuId] if (!product) return null return (

{product.name} x{item.quantity}

₹{product.price * item.quantity}

) })}

Total

₹{total}

) }