import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/Button';
import { Modal } from '@/components/ui/Modal';
import { PageContainer } from '@/components/ui/Typography';
import { PageHeader } from '@/components/layout/PageHeader';
import { Plus, Edit3, Trash2, Truck, BarChart3 } from 'lucide-react';
import { useShippingMethods, useDeleteShippingMethod } from '../core/_hooks';
import { ShippingMethod } from '../core/_models';

const ShippingMethodsListPage = () => {
    const navigate = useNavigate();
    const { data: methods, isLoading, error } = useShippingMethods();
    const { mutate: deleteMethod, isPending: isDeleting } = useDeleteShippingMethod();
    const [deleteId, setDeleteId] = useState<string | null>(null);

    const formatOpenHours = (openHours: ShippingMethod['open_hours']) => {
        if (!openHours || !openHours.length) return '-';
        return openHours.map((item) => `${item.from_hour}-${item.to_hour}`).join('، ');
    };

    const handleCreate = () => navigate('/shipping-methods/create');
    const handleEdit = (id: number) => navigate(`/shipping-methods/${id}/edit`);

    const handleDeleteConfirm = () => {
        if (!deleteId) return;
        deleteMethod(deleteId, { onSuccess: () => setDeleteId(null) });
    };

    const handleViewReport = (method: ShippingMethod) => {
        navigate(`/shipping-methods/shipments-report?shipping_method_id=${method.id}`);
    };

    if (isLoading) {
        return (
            <PageContainer>
                <div className="space-y-6">
                    <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
                        <div>
                            <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-64 mb-2 animate-pulse"></div>
                            <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-48 animate-pulse"></div>
                        </div>
                        <div className="h-12 w-12 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
                    </div>
                    <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                        <div className="overflow-x-auto">
                            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                <thead className="bg-gray-50 dark:bg-gray-700">
                                    <tr>
                                        {[...Array(7)].map((_, i) => (
                                            <th key={i} className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                                <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded w-20 animate-pulse"></div>
                                            </th>
                                        ))}
                                    </tr>
                                </thead>
                                <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    {[...Array(5)].map((_, i) => (
                                        <tr key={i} className="animate-pulse">
                                            {[...Array(7)].map((_, j) => (
                                                <td key={j} className="px-6 py-4 whitespace-nowrap">
                                                    <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded"></div>
                                                </td>
                                            ))}
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </PageContainer>
        );
    }

    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="space-y-6">
                <PageHeader
                    title="مدیریت روش‌های ارسال"
                    subtitle="تعریف و مدیریت روش‌های ارسال سفارش"
                    icon={Truck}
                    actions={
                        <button
                            onClick={handleCreate}
                            className="flex items-center justify-center w-12 h-12 bg-primary-600 hover:bg-primary-700 rounded-full transition-colors duration-200 text-white shadow-lg hover:shadow-xl"
                            title="روش ارسال جدید"
                        >
                            <Plus className="h-5 w-5" />
                        </button>
                    }
                />

                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                    <div className="hidden md:block">
                        <div className="overflow-x-auto">
                            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                <thead className="bg-gray-50 dark:bg-gray-700">
                                    <tr>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">نام</th>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">کد</th>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">محدوده وزن</th>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">ساعات پاسخگویی</th>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">اولویت</th>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">وضعیت</th>
                                        <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">عملیات</th>
                                    </tr>
                                </thead>
                                <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    {(methods || []).map((m: ShippingMethod) => (
                                        <tr key={m.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{m.name}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{m.code}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{m.min_weight} - {m.max_weight}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{formatOpenHours(m.open_hours)}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{m.priority}</td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm">
                                                <span className={`px-2 py-1 rounded-md text-xs ${m.enabled ? 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200' : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200'}`}>{m.enabled ? 'فعال' : 'غیرفعال'}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <div className="flex items-center gap-2">
                                                    <button
                                                        onClick={() => handleViewReport(m)}
                                                        className="text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300"
                                                        title="گزارش ارسال"
                                                    >
                                                        <BarChart3 className="h-4 w-4" />
                                                    </button>
                                                    <button onClick={() => handleEdit(m.id)} className="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300" title="ویرایش">
                                                        <Edit3 className="h-4 w-4" />
                                                    </button>
                                                    <button onClick={() => setDeleteId(m.id.toString())} className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300" title="حذف">
                                                        <Trash2 className="h-4 w-4" />
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Mobile */}
                    <div className="md:hidden p-4 space-y-4">
                        {(methods || []).map((m: ShippingMethod) => (
                            <div key={m.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                <div className="flex justify-between items-start mb-3">
                                    <div className="flex-1">
                                        <h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">{m.name}</h3>
                                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">کد: {m.code} • وزن: {m.min_weight}-{m.max_weight}</p>
                                    </div>
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">ساعات پاسخگویی: {formatOpenHours(m.open_hours)}</div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mb-3">اولویت: {m.priority}</div>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => handleViewReport(m)}
                                        className="flex items-center gap-1 px-2 py-1 text-xs text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300"
                                    >
                                        <BarChart3 className="h-3 w-3" />
                                        گزارش
                                    </button>
                                    <button onClick={() => handleEdit(m.id)} className="flex items-center gap-1 px-2 py-1 text-xs text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300">
                                        <Edit3 className="h-3 w-3" />
                                        ویرایش
                                    </button>
                                    <button onClick={() => setDeleteId(m.id.toString())} className="flex items-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">
                                        <Trash2 className="h-3 w-3" />
                                        حذف
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                <Modal isOpen={!!deleteId} onClose={() => setDeleteId(null)} title="حذف روش ارسال">
                    <div className="space-y-4">
                        <p className="text-gray-600 dark:text-gray-400">آیا از حذف این روش ارسال اطمینان دارید؟</p>
                        <div className="flex justify-end space-x-2 space-x-reverse">
                            <Button variant="secondary" onClick={() => setDeleteId(null)} disabled={isDeleting}>انصراف</Button>
                            <Button variant="danger" onClick={handleDeleteConfirm} loading={isDeleting}>حذف</Button>
                        </div>
                    </div>
                </Modal>
            </div>
        </PageContainer>
    );
};

export default ShippingMethodsListPage;


