import React, { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useOrder, useUpdateOrderStatus } from '../core/_hooks';
import { OrderStatus } from '../core/_models';
import { useShippingMethods } from '@/pages/shipping-methods/core/_hooks';
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { PageContainer, PageTitle, SectionTitle } from "@/components/ui/Typography";
import {
    ArrowRight,
    Package,
    User,
    CreditCard,
    MapPin,
    Calendar,
    Truck,
    Edit3,
    Phone,
    Mail,
    FileText
} from 'lucide-react';
import { englishToPersian } from '@/utils/numberUtils';
import { API_GATE_WAY } from '@/constant/routes';
import { formatCurrency, formatDateTime } from '@/utils/formatters';

const resolveImageUrl = (imageUrl?: string): string => {
    if (!imageUrl) return '';
    const trimmedUrl = imageUrl.trim();
    if (trimmedUrl.startsWith('http://') || trimmedUrl.startsWith('https://')) {
        return trimmedUrl;
    }
    return `${API_GATE_WAY}${trimmedUrl.startsWith('/') ? '' : '/'}${trimmedUrl}`;
};

const getStatusColor = (status: OrderStatus) => {
    const colors = {
        pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
        processing: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
        shipped: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
        delivered: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
        cancelled: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
        refunded: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200',
    };
    return colors[status] || colors.pending;
};

const getStatusText = (status: OrderStatus) => {
    const text = {
        pending: 'در انتظار',
        processing: 'در حال پردازش',
        shipped: 'ارسال شده',
        delivered: 'تحویل شده',
        cancelled: 'لغو شده',
        refunded: 'مرجوع شده',
    };
    return text[status] || status;
};


const formatPaymentType = (type?: string) => {
    if (!type) return '';
    const key = type.toLowerCase().replace(/\s+/g, '-').replace(/_/g, '-');
    const mapping: Record<string, string> = {
        'bank-topup': 'افزایش موجودی کیف پول',
        'card-to-card': 'پرداخت به روش کارت به کارت',
        'debit-rial-wallet': 'پرداخت از کیف ریالی',
        'debit-gold18k-wallet': 'پرداخت از کیف طلا',
        'credit-card': 'پرداخت بانکی',
        'debit-card': 'کارت بانکی',
        'bank-transfer': 'حواله بانکی',
        'cash-on-delivery': 'پرداخت در محل',
        'wallet': 'کیف پول',
    };
    return mapping[key] || type;
};

const OrderDetailPage = () => {
    const navigate = useNavigate();
    const { id } = useParams();
    const [statusUpdateOpen, setStatusUpdateOpen] = useState(false);
    const [newStatus, setNewStatus] = useState<OrderStatus>('processing');

    const { data, isLoading, error } = useOrder(id || '');
    const { mutate: updateStatus, isPending: isUpdating } = useUpdateOrderStatus();
    const { data: shippingMethods = [] } = useShippingMethods();
    const order = data?.order;

    const shippingMethod = order?.shipping_method_id
        ? shippingMethods.find(method => method.id === order.shipping_method_id)
        : null;
    const handleStatusUpdate = () => {
        if (id) {
            updateStatus(
                { id, payload: { status: newStatus } },
                { onSuccess: () => setStatusUpdateOpen(false) }
            );
        }
    };

    const handleUpdateStatusClick = () => {
        if (order) {
            setNewStatus(order?.status || 'pending');
            setStatusUpdateOpen(true);
        }
    };

    if (isLoading) {
        return (
            <PageContainer>
                <div className="space-y-6 animate-pulse">
                    <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-64"></div>
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <div className="lg:col-span-2 space-y-6">
                            {[...Array(3)].map((_, i) => (
                                <div key={i} className="card p-6">
                                    <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-4"></div>
                                    <div className="space-y-3">
                                        {[...Array(4)].map((_, j) => (
                                            <div key={j} className="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="space-y-6">
                            {[...Array(2)].map((_, i) => (
                                <div key={i} className="card p-6">
                                    <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-4"></div>
                                    <div className="space-y-3">
                                        {[...Array(3)].map((_, j) => (
                                            <div key={j} className="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </PageContainer>
        );
    }
    if (error || !order) {
        return (
            <PageContainer>
                <div className="text-center py-12">
                    <p className="text-red-600 dark:text-red-400">خطا در بارگذاری اطلاعات سفارش</p>
                    <Button variant="secondary" onClick={() => navigate('/orders')} className="mt-4">
                        بازگشت به لیست سفارشات
                    </Button>
                </div>
            </PageContainer>
        );
    }

    return (
        <PageContainer>
            {/* هدر صفحه */}
            <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
                <div>
                    <PageTitle>سفارش #{order?.order_number || 'نامشخص'}</PageTitle>
                    <p className="text-gray-600 dark:text-gray-400 mt-1">
                        تاریخ ثبت: {order?.created_at ? formatDateTime(order.created_at) : 'نامشخص'}
                    </p>
                </div>
                <div className="flex gap-3">
                    <Button
                        variant="secondary"
                        onClick={() => navigate('/orders')}
                        className="flex items-center gap-2"
                    >
                        <ArrowRight className="h-4 w-4" />
                        بازگشت
                    </Button>
                    <Button
                        variant="primary"
                        onClick={handleUpdateStatusClick}
                        className="flex items-center gap-2"
                    >
                        <Edit3 className="h-4 w-4" />
                        تغییر وضعیت
                    </Button>
                </div>
            </div>

            <div className="space-y-8">
                {/* اطلاعات کاربر سفارش‌دهنده و آدرس */}
                <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div className="bg-gradient-to-r from-indigo-50 to-blue-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-indigo-100 dark:bg-indigo-900 rounded-lg">
                                <User className="h-5 w-5 text-indigo-600 dark:text-indigo-300" />
                            </div>
                            <SectionTitle>اطلاعات مشتری و آدرس</SectionTitle>
                        </div>
                    </div>
                    <div className="p-6">
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                            {/* اطلاعات کاربر */}
                            <div className="space-y-4">
                                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4 flex items-center gap-2">
                                    <User className="h-5 w-5 text-indigo-600 dark:text-indigo-300" />
                                    اطلاعات کاربر
                                </h3>
                                {order?.user ? (
                                    <div className="space-y-4">
                                        <div className="flex items-start gap-3 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
                                            <div className="shrink-0">
                                                {order.user.avatar ? (
                                                    <img
                                                        src={order.user.avatar}
                                                        alt={`${order.user.first_name} ${order.user.last_name}`}
                                                        className="h-12 w-12 rounded-full object-cover border-2 border-indigo-200 dark:border-indigo-700"
                                                    />
                                                ) : (
                                                    <div className="h-12 w-12 rounded-full bg-indigo-100 dark:bg-indigo-900 flex items-center justify-center border-2 border-indigo-200 dark:border-indigo-700">
                                                        <span className="text-lg font-semibold text-indigo-600 dark:text-indigo-300">
                                                            {(order.user.first_name?.charAt(0) || '') + (order.user.last_name?.charAt(0) || '') || 'U'}
                                                        </span>
                                                    </div>
                                                )}
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <h4 className="font-semibold text-gray-900 dark:text-gray-100 mb-2 text-base">
                                                    {(order.user.first_name || 'نامشخص') + ' ' + (order.user.last_name || '')}
                                                </h4>
                                                <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${order.user.verified
                                                    ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                                                    : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'}`}
                                                >
                                                    {order.user.verified ? 'تأیید شده' : 'تأیید نشده'}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="space-y-3">
                                            <div className="flex items-start gap-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
                                                <Mail className="h-5 w-5 text-gray-400 shrink-0 mt-0.5" />
                                                <div className="flex-1 min-w-0">
                                                    <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">ایمیل</p>
                                                    <p className="text-sm font-medium text-gray-900 dark:text-gray-100 break-words">{order.user.email || 'ایمیل نامشخص'}</p>
                                                </div>
                                            </div>
                                            {order.user.phone_number && (
                                                <div className="flex items-start gap-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
                                                    <Phone className="h-5 w-5 text-gray-400 shrink-0 mt-0.5" />
                                                    <div className="flex-1 min-w-0">
                                                        <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">شماره تلفن</p>
                                                        <p className="text-sm font-medium text-gray-900 dark:text-gray-100 font-mono" dir="ltr" style={{ direction: 'ltr' }}>
                                                            {englishToPersian(order.user.phone_number)}
                                                        </p>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                ) : (
                                    <p className="text-gray-500 dark:text-gray-400">اطلاعات کاربر در دسترس نیست</p>
                                )}
                            </div>

                            {/* آدرس ارسال */}
                            <div className="space-y-4">
                                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4 flex items-center gap-2">
                                    <MapPin className="h-5 w-5 text-orange-600 dark:text-orange-300" />
                                    آدرس ارسال
                                </h3>
                                {order?.shipping_address ? (
                                    <div className="space-y-3">
                                        <div className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
                                            <div className="space-y-2.5 text-sm">
                                                {(order.shipping_address.first_name || order.shipping_address.last_name) && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">نام و نام خانوادگی:</span>
                                                        <span className="text-gray-900 dark:text-gray-100 break-words">
                                                            {[order.shipping_address.first_name, order.shipping_address.last_name].filter(Boolean).join(' ') || 'نامشخص'}
                                                        </span>
                                                    </div>
                                                )}
                                                {order.shipping_address.name && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">نام:</span>
                                                        <span className="text-gray-900 dark:text-gray-100 break-words">{order.shipping_address.name}</span>
                                                    </div>
                                                )}
                                                {order.shipping_address.address && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">آدرس:</span>
                                                        <span className="text-gray-900 dark:text-gray-100 break-words">{order.shipping_address.address}</span>
                                                    </div>
                                                )}
                                                {(order.shipping_address.city || order.shipping_address.state) && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">شهر/استان:</span>
                                                        <span className="text-gray-900 dark:text-gray-100">
                                                            {order.shipping_address.city || 'نامشخص'}{order.shipping_address.state ? `، ${order.shipping_address.state}` : ''}
                                                        </span>
                                                    </div>
                                                )}
                                                {order.shipping_address.region && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">منطقه:</span>
                                                        <span className="text-gray-900 dark:text-gray-100">{order.shipping_address.region}</span>
                                                    </div>
                                                )}
                                                {order.shipping_address.postal_code && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">کد پستی:</span>
                                                        <span className="text-gray-900 dark:text-gray-100 font-mono">{order.shipping_address.postal_code}</span>
                                                    </div>
                                                )}
                                                {order.shipping_address.plaque && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">پلاک/واحد:</span>
                                                        <span className="text-gray-900 dark:text-gray-100">
                                                            {order.shipping_address.plaque}{order.shipping_address.unit ? `، واحد ${order.shipping_address.unit}` : ''}
                                                        </span>
                                                    </div>
                                                )}
                                                {order.shipping_address.receiving_address && (
                                                    <div className="flex items-start gap-2">
                                                        <span className="font-medium text-gray-700 dark:text-gray-300 shrink-0 min-w-[80px]">آدرس تحویل:</span>
                                                        <span className="text-gray-900 dark:text-gray-100 break-words">{order.shipping_address.receiving_address}</span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                ) : (
                                    <p className="text-gray-500 dark:text-gray-400">آدرس ارسال در دسترس نیست</p>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                {/* اطلاعات سفارش */}
                <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div className="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
                                    <Package className="h-5 w-5 text-blue-600 dark:text-blue-300" />
                                </div>
                                <SectionTitle>اطلاعات سفارش</SectionTitle>
                            </div>
                            <span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(order?.status || 'pending')}`}>
                                {getStatusText(order?.status || 'pending')}
                            </span>
                        </div>
                    </div>
                    <div className="p-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            <div>
                                <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">شماره سفارش</h4>
                                <p className="text-gray-600 dark:text-gray-400">#{order?.order_number || 'نامشخص'}</p>
                            </div>
                            <div>
                                <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">تاریخ ثبت</h4>
                                <p className="text-gray-600 dark:text-gray-400">{order?.created_at ? formatDateTime(order.created_at) : 'نامشخص'}</p>
                            </div>
                            <div>
                                <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">شناسه فاکتور</h4>
                                <p className="text-gray-600 dark:text-gray-400 font-mono">{order?.invoice_id || 'نامشخص'}</p>
                            </div>
                            <div>
                                <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">شناسه کاربر</h4>
                                <p className="text-gray-600 dark:text-gray-400">{order?.user_id || 'نامشخص'}</p>
                            </div>
                            <div>
                                <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">تاریخ آخرین بروزرسانی</h4>
                                <p className="text-gray-600 dark:text-gray-400">{order?.updated_at ? formatDateTime(order.updated_at) : 'نامشخص'}</p>
                            </div>
                            {/* روش حمل و نقل در داده‌های فعلی وجود ندارد */}
                            {order?.tracking_number && (
                                <div>
                                    <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">کد رهگیری</h4>
                                    <p className="text-gray-600 dark:text-gray-400 font-mono">{order.tracking_number}</p>
                                </div>
                            )}
                            {order?.estimated_delivery && (
                                <div>
                                    <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">تاریخ تحویل تخمینی</h4>
                                    <p className="text-gray-600 dark:text-gray-400">{formatDateTime(order.estimated_delivery)}</p>
                                </div>
                            )}
                            {order?.shipping_method_id !== undefined && order?.shipping_method_id !== null && (
                                <div>
                                    <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">متد ارسال</h4>
                                    <p className="text-gray-600 dark:text-gray-400">
                                        {shippingMethod
                                            ? shippingMethod.name
                                            : shippingMethods.length === 0
                                                ? `شناسه: ${order.shipping_method_id} (در حال بارگذاری...)`
                                                : `شناسه: ${order.shipping_method_id}`
                                        }
                                    </p>
                                </div>
                            )}
                            {order?.selected_delivery_slot && (
                                <div>
                                    <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">زمان تحویل انتخاب شده</h4>
                                    <p className="text-gray-600 dark:text-gray-400">
                                        {typeof order.selected_delivery_slot === 'object'
                                            ? `${order.selected_delivery_slot.date || ''} ${order.selected_delivery_slot.from_hour || ''}:${order.selected_delivery_slot.to_hour || ''}`
                                            : String(order.selected_delivery_slot)
                                        }
                                    </p>
                                </div>
                            )}
                        </div>
                        {order?.notes && (
                            <div className="mt-6">
                                <h4 className="font-medium text-gray-900 dark:text-gray-100 mb-2">یادداشت</h4>
                                <p className="text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-gray-700 p-3 rounded-lg">
                                    {order.notes}
                                </p>
                            </div>
                        )}
                    </div>
                </div>

                {/* آیتم‌های سفارش */}
                <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div className="bg-gradient-to-r from-green-50 to-emerald-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
                                <Package className="h-5 w-5 text-green-600 dark:text-green-300" />
                            </div>
                            <SectionTitle>محصولات سفارش</SectionTitle>
                        </div>
                    </div>
                    <div className="p-0">
                        {order?.items && order.items.length > 0 ? (
                            <div className="space-y-4">
                                {order.items.map((item) => {
                                    const baseWeight = (item.weight ?? 0) as number;
                                    const weightGr = Math.round(baseWeight * 1000);
                                    const formatFa = (n: number) => new Intl.NumberFormat('fa-IR').format(n);
                                    const imageUrl = item.image_url || item.product_image;
                                    return (
                                        <div key={item.id} className="px-4 md:px-6 py-3">
                                            <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4 md:p-5 shadow-sm">
                                                <div className="flex items-start justify-between gap-4">
                                                    <div className="flex items-start gap-3 min-w-0 flex-1">
                                                        {imageUrl && (
                                                            <div className="shrink-0">
                                                                <img
                                                                    src={resolveImageUrl(imageUrl)}
                                                                    alt={item.product_name || 'محصول'}
                                                                    className="w-16 h-16 md:w-20 md:h-20 rounded-lg object-cover border border-gray-200 dark:border-gray-600"
                                                                    onError={(e) => {
                                                                        const target = e.target as HTMLImageElement;
                                                                        target.style.display = 'none';
                                                                    }}
                                                                />
                                                            </div>
                                                        )}
                                                        <div className="min-w-0 flex-1">
                                                            <div className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">
                                                                {item.product_name || `محصول شناسه: ${item.product_id}`}
                                                            </div>
                                                            <div className="text-xs text-gray-500 dark:text-gray-400 mt-1 truncate">
                                                                {item.product_variant_name || `واریانت شناسه: ${item.product_variant_id}`}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="text-left shrink-0">
                                                        <div className="text-xs text-gray-500 dark:text-gray-400">جمع</div>
                                                        <div className="text-base md:text-lg font-bold text-gray-900 dark:text-gray-100">{formatCurrency(item.total_price || 0)}</div>
                                                    </div>
                                                </div>
                                                <div className="mt-4 grid grid-cols-2 md:grid-cols-4 gap-3">
                                                    <div className="rounded-lg bg-gray-50 dark:bg-gray-700/50 px-3 py-2 border border-gray-200 dark:border-gray-600">
                                                        <div className="text-[11px] text-gray-500 dark:text-gray-400">تعداد</div>
                                                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{formatFa(item.quantity || 0)}</div>
                                                    </div>
                                                    <div className="rounded-lg bg-gray-50 dark:bg-gray-700/50 px-3 py-2 border border-gray-200 dark:border-gray-600">
                                                        <div className="text-[11px] text-gray-500 dark:text-gray-400">وزن (گرم)</div>
                                                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{formatFa(weightGr)}</div>
                                                    </div>
                                                    <div className="rounded-lg bg-gray-50 dark:bg-gray-700/50 px-3 py-2 border border-gray-200 dark:border-gray-600 col-span-2 md:col-span-2">
                                                        <div className="flex items-center justify-between">
                                                            <div className="text-[11px] text-gray-500 dark:text-gray-400">قیمت واحد</div>
                                                            <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{formatCurrency(item.unit_price || 0)}</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        ) : (
                            <p className="text-gray-500 dark:text-gray-400 text-center py-6">
                                محصولی در این سفارش یافت نشد
                            </p>
                        )}
                    </div>
                </div>

                {/* اطلاعات پرداخت */}
                <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
                    <div className="bg-gradient-to-r from-teal-50 to-cyan-50 dark:from-gray-700 dark:to-gray-600 px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-teal-100 dark:bg-teal-900 rounded-lg">
                                <CreditCard className="h-5 w-5 text-teal-600 dark:text-teal-300" />
                            </div>
                            <SectionTitle>پرداخت</SectionTitle>
                        </div>
                    </div>
                    <div className="p-6 space-y-4 overflow-hidden">
                        <div className="flex items-center justify-between text-base gap-2">
                            <span className="text-gray-800 dark:text-gray-200 shrink-0">جمع اقلام</span>
                            <span className="font-medium text-gray-900 dark:text-gray-100 break-all text-left">{formatCurrency(order?.net_total || 0)}</span>
                        </div>
                        <div className="flex items-center justify-between text-base gap-2">
                            <span className="text-gray-800 dark:text-gray-200 shrink-0">مالیات</span>
                            <span className="font-medium text-gray-900 dark:text-gray-100 break-all text-left">{formatCurrency(order?.vat_total || 0)}</span>
                        </div>
                        {order?.base_gold_price !== undefined && (
                            <div className="flex items-center justify-between text-base gap-2">
                                <span className="text-gray-800 dark:text-gray-200 shrink-0">قیمت پایه طلا</span>
                                <span className="font-medium text-gray-900 dark:text-gray-100 break-all text-left">{formatCurrency(order.base_gold_price)}</span>
                            </div>
                        )}
                        <div className="flex items-center justify-between text-base gap-2">
                            <span className="text-gray-800 dark:text-gray-200 shrink-0">هزینه ارسال</span>
                            <span className="font-medium text-gray-900 dark:text-gray-100 break-all text-left">{formatCurrency(order?.shipping_total || 0)}</span>
                        </div>
                        {(order?.discount_total || 0) > 0 && (
                            <div className="flex justify-between text-green-600 dark:text-green-400 gap-2">
                                <span className="shrink-0">تخفیف کل</span>
                                <span className="font-medium break-all text-left">-{formatCurrency(order?.discount_total || 0)}</span>
                            </div>
                        )}
                        <hr className="border-gray-200 dark:border-gray-700" />
                        <div className="flex items-center justify-between text-lg font-bold gap-2">
                            <span className="text-gray-900 dark:text-gray-100 shrink-0">مجموع نهایی</span>
                            <span className="text-gray-900 dark:text-gray-100 break-all text-left">{formatCurrency(order?.final_total || 0)}</span>
                        </div>

                        <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                            <div className="space-y-2">
                                <div className="flex items-center justify-between text-base gap-2">
                                    <span className="text-gray-700 dark:text-gray-200 shrink-0">وضعیت پرداخت</span>
                                    <span className={`text-sm font-medium px-2 py-1 rounded-full shrink-0 ${order?.payment_status === 'paid'
                                        ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                                        : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
                                        }`}>
                                        {order?.payment_status === 'paid' ? 'پرداخت شده' : 'در انتظار پرداخت'}
                                    </span>
                                </div>
                                {Array.isArray((data as any)?.payments) && (data as any)?.payments.length > 0 && (
                                    <div className="flex items-center justify-between text-base gap-2">
                                        <span className="text-gray-700 dark:text-gray-200 shrink-0">روش پرداخت</span>
                                        <span className="text-gray-900 dark:text-gray-100 break-words text-left">{formatPaymentType((data as any).payments[0].payment_type)}</span>
                                    </div>
                                )}
                                {order?.invoice_id && (
                                    <div className="flex items-start justify-between text-base gap-2">
                                        <span className="text-gray-700 dark:text-gray-200 shrink-0">شماره فاکتور</span>
                                        <span className="font-mono text-gray-900 dark:text-gray-100 break-all text-left text-sm">{order.invoice_id}</span>
                                    </div>
                                )}
                                {Array.isArray((data as any)?.payments) && (data as any)?.payments[0]?.transaction_id && (
                                    <div className="flex items-start justify-between text-base gap-2">
                                        <span className="text-gray-700 dark:text-gray-200 shrink-0">شناسه تراکنش</span>
                                        <span className="font-mono text-gray-900 dark:text-gray-100 break-all text-left text-sm">{(data as any).payments[0].transaction_id}</span>
                                    </div>
                                )}
                                {Array.isArray((data as any)?.payments) && (data as any)?.payments[0]?.image_urls?.length > 0 && (
                                    <div className="flex items-center justify-between text-base gap-2">
                                        <span className="text-gray-700 dark:text-gray-200 shrink-0">رسید پرداخت</span>
                                        <a href={(data as any).payments[0].image_urls[0]} target="_blank" rel="noreferrer" className="shrink-0">
                                            <img src={(data as any).payments[0].image_urls[0]} alt="رسید پرداخت" className="h-14 w-14 rounded-md object-cover border border-gray-200 dark:border-gray-600" />
                                        </a>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* مودال تغییر وضعیت */}
            <Modal isOpen={statusUpdateOpen} onClose={() => setStatusUpdateOpen(false)} title="تغییر وضعیت سفارش">
                <div className="space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            وضعیت جدید
                        </label>
                        <select
                            value={newStatus}
                            onChange={(e) => setNewStatus(e.target.value as OrderStatus)}
                            className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                        >
                            <option value="pending">در انتظار</option>
                            <option value="processing">در حال پردازش</option>
                            <option value="shipped">ارسال شده</option>
                            <option value="delivered">تحویل شده</option>
                            <option value="cancelled">لغو شده</option>
                            <option value="refunded">مرجوع شده</option>
                        </select>
                    </div>
                    <div className="flex justify-end space-x-2 space-x-reverse">
                        <Button variant="secondary" onClick={() => setStatusUpdateOpen(false)} disabled={isUpdating}>
                            انصراف
                        </Button>
                        <Button variant="primary" onClick={handleStatusUpdate} loading={isUpdating}>
                            به‌روزرسانی
                        </Button>
                    </div>
                </div>
            </Modal>
        </PageContainer>
    );
};

export default OrderDetailPage;
