"use client"; import { useState } from "react"; import Image from "next/image"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Skeleton } from "@/components/ui/skeleton"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { useToast } from "@/hooks/use-toast"; import { useOrders, useCancelOrder } from "@/lib/hooks"; import type { Order } from "../types"; export default function OrdersPageClient() { const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false); const [orderToCancel, setOrderToCancel] = useState(null); const { toast } = useToast(); const { data: orders, isLoading, isError, error } = useOrders(); const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder(); const t = { myOrders: "Мои заказы", activeOrders: "Активные заказы", completedOrders: "Завершенные заказы", cancelOrder: "Отменить заказ", keepOrder: "Оставить заказ", cancelConfirmation: "Вы уверены, что хотите отменить этот заказ?", cancelling: "Отмена...", orderNumber: "Заказ №", ordered: "Заказано", completed: "Завершено", estimatedDelivery: "Ожид. доставка", quantity: "Кол-во", total: "Итого", noOrders: "У вас пока нет заказов", noActiveOrders: "У вас нет активных заказов", noCompletedOrders: "У вас нет завершенных заказов", loadError: "Не удалось загрузить заказы", orderCancelled: "Заказ отменен", orderCancelledDescription: "Ваш заказ был успешно отменен", error: "Ошибка", status: "Статус", deliveryTime: "Время доставки", deliveryDate: "Дата доставки", address: "Адрес", paymentMethod: "Способ оплаты", }; const handleCancelOrder = (order: Order) => { setOrderToCancel(order); setIsCancelDialogOpen(true); }; const confirmCancelOrder = () => { if (!orderToCancel) return; cancelOrder(orderToCancel.id, { onSuccess: () => { toast({ title: t.orderCancelled, description: t.orderCancelledDescription, }); setIsCancelDialogOpen(false); setOrderToCancel(null); }, onError: (error: any) => { toast({ title: t.error, description: error.message || "Не удалось отменить заказ", variant: "destructive", }); }, }); }; const getStatusBadge = (status: string) => { const lowerStatus = status.toLowerCase(); if (lowerStatus.includes("ожидается") || lowerStatus.includes("pending")) { return {status}; } if (lowerStatus.includes("обработка") || lowerStatus.includes("processing")) { return {status}; } if (lowerStatus.includes("отправлен") || lowerStatus.includes("shipped")) { return {status}; } if (lowerStatus.includes("доставлен") || lowerStatus.includes("delivered")) { return {status}; } if (lowerStatus.includes("отменен") || lowerStatus.includes("cancelled")) { return {status}; } return {status}; }; const isActiveOrder = (status: string) => { const lower = status.toLowerCase(); return lower.includes("ожидается") || lower.includes("обработка") || lower.includes("отправлен") || lower.includes("pending") || lower.includes("processing") || lower.includes("shipped"); }; const activeOrders = orders?.filter((o) => isActiveOrder(o.status)) || []; const completedOrders = orders?.filter((o) => !isActiveOrder(o.status)) || []; const calculateTotal = (order: Order) => { return order.orderItems.reduce((sum, item) => { return sum + (parseFloat(item.unit_price_amount) * item.quantity); }, 0); }; if (isLoading) { return (

{t.myOrders}

{Array.from({ length: 6 }).map((_, i) => ( ))}
); } if (isError) { return (

{t.myOrders}

{t.loadError}

); } if (!orders || orders.length === 0) { return (

{t.myOrders}

{t.noOrders}

); } return (

{t.myOrders}

{t.activeOrders} ({activeOrders.length}) {t.completedOrders} ({completedOrders.length}) {activeOrders.length === 0 ? (

{t.noActiveOrders}

) : (
{activeOrders.map((order) => ( ))}
)}
{completedOrders.length === 0 ? (

{t.noCompletedOrders}

) : (
{completedOrders.map((order) => ( ))}
)}
{t.cancelOrder} #{orderToCancel?.id} {t.cancelConfirmation}
); } interface OrderCardProps { order: Order; onCancel: (order: Order) => void; isCancelling: boolean; getStatusBadge: (status: string) => React.ReactNode; calculateTotal: (order: Order) => number; translations: any; showCancelButton: boolean; } function OrderCard({ order, onCancel, isCancelling, getStatusBadge, calculateTotal, translations: t, showCancelButton, }: OrderCardProps) { const total = calculateTotal(order); return (

{t.orderNumber}{order.id}

{getStatusBadge(order.status)}

{t.deliveryTime}: {order.delivery_time}

{t.deliveryDate}:{" "} {new Date(order.delivery_at).toLocaleDateString()}

{t.address}: {order.customer_address}

{t.paymentMethod}: {order.payment_type}

{order.orderItems.map((item, index) => (
{item.product.name}

{item.product.name}

{t.quantity}: {item.quantity} × {item.unit_price_amount} TMT

))}
{t.total} {total.toFixed(2)} TMT
{showCancelButton && (
)}
); }