import React, { useMemo, useState } from 'react';
import { englishToPersian } from '@/utils/numberUtils';
import { useNavigate } from 'react-router-dom';
import { useOrders, useOrderStats, useUpdateOrderStatus } from '../core/_hooks';
import { Order, OrderFilters, OrderStatus } from '../core/_models';
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Modal } from "@/components/ui/Modal";
import { Pagination } from "@/components/ui/Pagination";
import { PageContainer, PageTitle, SectionTitle } from "@/components/ui/Typography";
import { Table } from "@/components/ui/Table";
import { TableColumn } from "@/types";
import {
    ShoppingCart,
    Package,
    DollarSign,
    Clock,
    Search,
    Filter,
    Eye,
    Edit3,
    TrendingUp,
    Calendar
} from 'lucide-react';

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 formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('fa-IR').format(amount) + ' تومان';
};

const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('fa-IR');
};

const ListSkeleton = () => (
    <Table columns={[]} data={[]} loading={true} />
);

const OrdersListPage = () => {
    const navigate = useNavigate();
    const [statusUpdateId, setStatusUpdateId] = useState<string | null>(null);
    const [newStatus, setNewStatus] = useState<OrderStatus>('processing');
    const [filters, setFilters] = useState<OrderFilters>({
        page: 1,
        limit: 20,
        order_number: '',
        status: 'pending',
        payment_status: undefined,
        search: '',
    });

    const { data: ordersData, isLoading, error } = useOrders(filters);
    // Temporarily disabled stats API
    // const { data: stats, isLoading: statsLoading } = useOrderStats(!isLoading);
    const stats = null;
    const statsLoading = false;
    const { mutate: updateStatus, isPending: isUpdating } = useUpdateOrderStatus();


    const columns: TableColumn[] = useMemo(() => [
        { key: 'order_number', label: 'شماره سفارش', sortable: true, align: 'right', render: (v: string) => `#${v}` },
        {
            key: 'customer',
            label: 'مشتری',
            align: 'right',
            render: (_val, row: any) => (
                <div className="text-right">
                    <div className="font-medium">
                        {(row.user?.first_name || row.customer?.first_name || 'نامشخص')} {(row.user?.last_name || row.customer?.last_name || '')}
                    </div>
                    <div className="text-gray-500 dark:text-gray-400" dir="ltr" style={{ direction: 'ltr' }}>
                        {row.user?.phone_number ? englishToPersian(row.user.phone_number) : '-'}
                    </div>
                </div>
            )
        },
        { key: 'final_total', label: 'مبلغ نهایی', sortable: true, align: 'right', render: (v: number, row: any) => formatCurrency(row.final_total || row.total_amount || 0) },
        { key: 'status', label: 'وضعیت', align: 'right', render: (v: OrderStatus) => (<span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(v)}`}>{getStatusText(v)}</span>) },
        { key: 'created_at', label: 'تاریخ', sortable: true, align: 'right', render: (v: string) => formatDate(v) },
        {
            key: 'actions',
            label: 'عملیات',
            align: 'right',
            render: (_val, row: any) => (
                <div className="flex items-center gap-2 justify-end">
                    <button
                        onClick={() => handleViewOrder(row.id)}
                        className="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300"
                        title="مشاهده جزئیات"
                    >
                        <Eye className="h-4 w-4" />
                    </button>
                    <button
                        onClick={() => handleUpdateStatus(row.id, row.status)}
                        className="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300"
                        title="تغییر وضعیت"
                    >
                        <Edit3 className="h-4 w-4" />
                    </button>
                </div>
            )
        },
    ], []);

    const handleStatusUpdate = () => {
        if (statusUpdateId) {
            updateStatus(
                { id: statusUpdateId, payload: { status: newStatus } },
                { onSuccess: () => setStatusUpdateId(null) }
            );
        }
    };

    const handleViewOrder = (id: number) => {
        navigate(`/orders/${id}`);
    };

    const handleUpdateStatus = (id: number, currentStatus: OrderStatus) => {
        setStatusUpdateId(id.toString());
        setNewStatus(currentStatus);
    };

    const handlePageChange = (page: number) => {
        setFilters(prev => ({ ...prev, page }));
    };

    if (error) {
        return (
            <PageContainer>
                <div className="text-center py-12">
                    <p className="text-red-600 dark:text-red-400">خطا در بارگذاری سفارشات</p>
                </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 className="flex items-center gap-2">
                        <ShoppingCart className="h-6 w-6" />
                        مدیریت سفارشات
                    </PageTitle>
                    <p className="text-gray-600 dark:text-gray-400 mt-1">
                        {ordersData?.total || 0} سفارش یافت شد
                    </p>
                </div>
            </div>

            {/* آمار کلی */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                    <div className="flex items-center">
                        <div className="p-3 bg-blue-100 dark:bg-blue-900 rounded-lg">
                            <ShoppingCart className="h-6 w-6 text-blue-600 dark:text-blue-300" />
                        </div>
                        <div className="mr-4">
                            <p className="text-sm font-medium text-gray-600 dark:text-gray-400">کل سفارشات</p>
                            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                --
                            </p>
                        </div>
                    </div>
                </div>

                <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                    <div className="flex items-center">
                        <div className="p-3 bg-green-100 dark:bg-green-900 rounded-lg">
                            <DollarSign className="h-6 w-6 text-green-600 dark:text-green-300" />
                        </div>
                        <div className="mr-4">
                            <p className="text-sm font-medium text-gray-600 dark:text-gray-400">کل فروش</p>
                            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                --
                            </p>
                        </div>
                    </div>
                </div>

                <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                    <div className="flex items-center">
                        <div className="p-3 bg-yellow-100 dark:bg-yellow-900 rounded-lg">
                            <Clock className="h-6 w-6 text-yellow-600 dark:text-yellow-300" />
                        </div>
                        <div className="mr-4">
                            <p className="text-sm font-medium text-gray-600 dark:text-gray-400">در انتظار</p>
                            <p className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                --
                            </p>
                        </div>
                    </div>
                </div>

                <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                    <div className="flex items-center">
                        <div className="p-3 bg-purple-100 dark:bg-purple-900 rounded-lg">
                            <TrendingUp className="h-6 w-6 text-purple-600 dark:text-purple-300" />
                        </div>
                        <div className="mr-4">
                            <p className="text-sm font-medium text-gray-600 dark:text-gray-400">میانگین سفارش</p>
                            <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                                --
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            {/* فیلترها */}
            <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="relative col-span-1 md:col-span-2 lg:col-span-4 order-first">
                        <Search className="absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400 dark:text-gray-300" />
                        <input
                            type="text"
                            placeholder="جستجو عمومی (شماره سفارش، کد تراکنش، کد تخفیف)..."
                            value={filters.search || ''}
                            onChange={(e) => setFilters(prev => ({ ...prev, search: e.target.value, page: 1 }))}
                            className="w-full pr-10 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-300"
                        />
                    </div>

                    <div>
                        <select
                            value={filters.status || ''}
                            onChange={(e) => setFilters(prev => ({ ...prev, status: e.target.value as OrderStatus || undefined, page: 1 }))}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        >
                            <option value="">همه وضعیت‌ها</option>
                            <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>
                        <select
                            value={filters.payment_status || ''}
                            onChange={(e) => setFilters(prev => ({ ...prev, payment_status: e.target.value as any || undefined, page: 1 }))}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        >
                            <option value="">همه وضعیت‌های پرداخت</option>
                            <option value="pending">در انتظار پرداخت</option>
                            <option value="paid">پرداخت شده</option>
                            <option value="failed">پرداخت ناموفق</option>
                            <option value="refunded">بازپرداخت شده</option>
                            <option value="cancelled">لغو شده</option>
                        </select>
                    </div>

                    <Button
                        variant="secondary"
                        onClick={() => setFilters({ page: 1, limit: 20, order_number: '', status: undefined, payment_status: undefined, search: '' })}
                        className="flex items-center gap-2"
                    >
                        <Filter className="h-4 w-4" />
                        پاک کردن فیلترها
                    </Button>
                </div>
            </div>

            {/* جدول سفارشات */}
            {isLoading ? (
                <ListSkeleton />
            ) : !ordersData?.orders || ordersData.orders.length === 0 ? (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                    <div className="text-center py-12">
                        <ShoppingCart className="h-12 w-12 text-gray-400 dark:text-gray-500 mx-auto mb-4" />
                        <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">هیچ سفارشی یافت نشد</h3>
                        <p className="text-gray-600 dark:text-gray-400">با تغییر فیلترها جستجو کنید</p>
                    </div>
                </div>
            ) : (
                <>
                    <Table columns={columns} data={ordersData.orders as any[]} />
                    <Pagination
                        currentPage={filters.page || 1}
                        totalPages={Math.ceil((ordersData.total || 0) / (filters.limit || 20))}
                        onPageChange={handlePageChange}
                        itemsPerPage={filters.limit || 20}
                        totalItems={ordersData.total || 0}
                    />
                </>
            )}

            {/* مودال تغییر وضعیت */}
            <Modal isOpen={!!statusUpdateId} onClose={() => setStatusUpdateId(null)} 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-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        >
                            <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={() => setStatusUpdateId(null)} disabled={isUpdating}>
                            انصراف
                        </Button>
                        <Button variant="primary" onClick={handleStatusUpdate} loading={isUpdating}>
                            به‌روزرسانی
                        </Button>
                    </div>
                </div>
            </Modal>
        </PageContainer>
    );
};

export default OrdersListPage;
