import { useState } from "react"; import { useLocation } from "wouter"; import { useAuth } from "@/hooks/use-auth"; import { useCart } from "@/hooks/use-cart"; import { ordersApi } from "@/lib/api"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import Header from "@/components/layout/header"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Separator } from "@/components/ui/separator"; import { useToast } from "@/hooks/use-toast"; import { Loader2, CreditCard, Shield, IndianRupee, Smartphone } from "lucide-react"; import { INDIAN_STATES, PAYMENT_METHODS, DEFAULT_COUNTRY } from "@/lib/constants"; const checkoutSchema = z.object({ firstName: z.string().min(1, "First name is required"), lastName: z.string().min(1, "Last name is required"), email: z.string().email("Valid email is required"), phone: z.string().min(10, "Phone number is required"), street: z.string().min(1, "Street address is required"), city: z.string().min(1, "City is required"), state: z.string().min(1, "State is required"), pinCode: z.string().min(6, "PIN code is required").max(6, "PIN code must be 6 digits"), country: z.string().min(1, "Country is required"), paymentMethod: z.enum(["cod", "upi"], { required_error: "Please select a payment method" }), upiId: z.string().optional(), }).refine((data) => { if (data.paymentMethod === "upi" && (!data.upiId || data.upiId.length === 0)) { return false; } return true; }, { message: "UPI ID is required for UPI payment", path: ["upiId"] }); type CheckoutFormData = z.infer; export default function Checkout() { const [, setLocation] = useLocation(); const { user } = useAuth(); const { items, subtotal, tax, total, clearCart } = useCart(); const { toast } = useToast(); const [isLoading, setIsLoading] = useState(false); const [searchQuery, setSearchQuery] = useState(""); const form = useForm({ resolver: zodResolver(checkoutSchema), defaultValues: { firstName: user?.firstName || "", lastName: user?.lastName || "", email: user?.email || "", phone: user?.phone || "", street: user?.street || "", city: user?.city || "", state: user?.state || "", pinCode: user?.zipCode || "", country: user?.country || DEFAULT_COUNTRY, paymentMethod: "cod" as const, upiId: "", }, }); // Redirect if not authenticated or cart is empty if (!user) { setLocation('/auth'); return null; } if (items.length === 0) { setLocation('/'); return null; } const onSubmit = async (data: CheckoutFormData) => { setIsLoading(true); try { const shippingAddress = `${data.street}, ${data.city}, ${data.state} ${data.pinCode}, ${data.country}`; const orderData = { subtotal: subtotal.toString(), tax: tax.toString(), shipping: "0.00", total: total.toString(), shippingAddress, paymentMethod: data.paymentMethod, items: items.map(item => ({ productId: item.productId, quantity: item.quantity, price: item.product?.price || "0", })), }; await ordersApi.create(orderData); clearCart(); toast({ title: "Order placed successfully!", description: "Thank you for your purchase. You will receive a confirmation email shortly.", }); setLocation('/profile'); } catch (error) { toast({ variant: "destructive", title: "Order failed", description: "There was an error processing your order. Please try again.", }); } finally { setIsLoading(false); } }; return (

Checkout

Complete your purchase

{/* Checkout Form */}
{/* User Details Confirmation */} Confirm Your Details

Please confirm that your details below are correct:

Name: {user?.firstName} {user?.lastName}
Email: {user?.email}
Phone: {user?.phone}
Address: {user?.street}
City: {user?.city}
State: {user?.state}
{/* Shipping Information */} Shipping Information
( First Name )} /> ( Last Name )} />
( Email Address )} /> ( Phone Number )} />
( Street Address )} />
( City )} /> ( State )} /> ( PIN Code )} />
{/* Payment Information */} Payment Method ( Select Payment Method )} /> {form.watch("paymentMethod") === "upi" && ( ( UPI ID )} /> )}

{form.watch("paymentMethod") === "cod" ? "Pay with cash when your order is delivered" : "Secure UPI payment gateway" }

{/* Order Summary */}
Order Summary {/* Order Items */}
{items.map((item) => (
{item.product?.images && item.product.images.length > 0 ? ( {item.product.title} ) : (
No Image
)}

{item.product?.title || 'Unknown Product'}

{item.product?.store?.name || 'Unknown Seller'}

Qty: {item.quantity} ₹{item.product ? (parseFloat(item.product.price) * item.quantity).toFixed(2) : '0.00'}
))}
{/* Order Totals */}
Subtotal: ₹{subtotal.toFixed(2)}
Shipping: Free
Tax: ₹{tax.toFixed(2)}
Total: ₹{total.toFixed(2)}
); }