import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useProducts, useDeleteProduct } from '../core/_hooks';
import { useCategories } from '../../categories/core/_hooks';
import { Product } from '../core/_models';
import { Button } from "@/components/ui/Button";

import { Trash2, Edit3, Plus, Package, Eye, Image } from "lucide-react";
import { Modal } from "@/components/ui/Modal";
import { persianToEnglish } from '../../../utils/numberUtils';
import { Pagination } from "@/components/ui/Pagination";

const ProductsTableSkeleton = () => (
    <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>
                        </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}>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded animate-pulse"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded animate-pulse"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded animate-pulse"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-200 dark:bg-gray-600 rounded animate-pulse"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="flex gap-2">
                                        <div className="h-8 w-8 bg-gray-200 dark:bg-gray-600 rounded animate-pulse"></div>
                                        <div className="h-8 w-8 bg-gray-200 dark:bg-gray-600 rounded animate-pulse"></div>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
);

const ProductsListPage = () => {
    const navigate = useNavigate();
    const [deleteProductId, setDeleteProductId] = useState<string | null>(null);
    const [filters, setFilters] = useState({
        search: '',
        category_id: '',
        status: '',
        min_price: '',
        max_price: '',
        page: 1,
        limit: 100,
    });

    const { data: productsData, isLoading, error } = useProducts({
        ...filters,
        category_id: filters.category_id ? Number(filters.category_id) : undefined,
        min_price: filters.min_price ? Number(filters.min_price) : undefined,
        max_price: filters.max_price ? Number(filters.max_price) : undefined,
    });
    const { data: categories } = useCategories();
    const { mutate: deleteProduct, isPending: isDeleting } = useDeleteProduct();

    const products = productsData?.products || [];

    const handleCreate = () => {
        navigate('/products/create');
    };

    const handleEdit = (productId: number) => {
        navigate(`/products/${productId}/edit`);
    };

    const handleView = (productId: number) => {
        navigate(`/products/${productId}`);
    };

    const handleDeleteConfirm = () => {
        if (deleteProductId) {
            deleteProduct(deleteProductId, {
                onSuccess: () => {
                    setDeleteProductId(null);
                }
            });
        }
    };

    const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setFilters(prev => ({ ...prev, search: e.target.value, page: 1 }));
    };

    const handleCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setFilters(prev => ({ ...prev, category_id: e.target.value, page: 1 }));
    };

    const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setFilters(prev => ({ ...prev, status: e.target.value, page: 1 }));
    };

    const formatPrice = (price: number) => {
        return new Intl.NumberFormat('fa-IR').format(price) + ' تومان';
    };

    const getFirstImageUrl = (p: any): string | null => {
        if (p.file_ids && p.file_ids.length > 0) return p.file_ids[0].url;
        if (p.files && p.files.length > 0) return p.files[0].url;
        return null;
    };

    const getStatusBadge = (status: string) => {
        switch (status) {
            case 'active':
                return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">فعال</span>;
            case 'inactive':
                return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200">غیرفعال</span>;
            case 'draft':
                return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200">پیش‌نویس</span>;
            default:
                return <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200">{status}</span>;
        }
    };

    const total = productsData?.total || 0;
    const currentPage = productsData?.page || filters.page;
    const perPage = productsData?.per_page || filters.limit;
    const totalPages = Math.max(1, Math.ceil((total || 0) / (perPage || 20)));

    if (error) {
        return (
            <div className="p-6">
                <div className="text-center py-12">
                    <p className="text-red-600 dark:text-red-400">خطا در بارگذاری محصولات</p>
                </div>
            </div>
        );
    }

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-2">
                        <Package className="h-6 w-6" />
                        مدیریت محصولات
                    </h1>
                    <p className="text-gray-600 dark:text-gray-400 mt-1">
                        مدیریت محصولات، قیمت‌ها و موجودی
                    </p>
                </div>
                <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>

            {/* Filters */}
            <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            جستجو
                        </label>
                        <input
                            type="text"
                            placeholder="جستجو در نام محصول..."
                            value={filters.search}
                            onChange={handleSearchChange}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            دسته‌بندی
                        </label>
                        <select
                            value={filters.category_id}
                            onChange={handleCategoryChange}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        >
                            <option value="">همه دسته‌بندی‌ها</option>
                            {(categories || []).map((category) => (
                                <option key={category.id} value={category.id}>
                                    {category.name}
                                </option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            وضعیت
                        </label>
                        <select
                            value={filters.status}
                            onChange={handleStatusChange}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                        >
                            <option value="">همه وضعیت‌ها</option>
                            <option value="active">فعال</option>
                            <option value="inactive">غیرفعال</option>
                            <option value="draft">پیش‌نویس</option>
                        </select>
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            محدوده قیمت
                        </label>
                        <div className="flex gap-2">
                            <input
                                type="text"
                                inputMode="numeric"
                                placeholder="حداقل (مثال: ۱۰۰۰۰)"
                                value={filters.min_price}
                                onChange={(e) => {
                                    const converted = persianToEnglish(e.target.value);
                                    setFilters(prev => ({ ...prev, min_price: converted, page: 1 }));
                                }}
                                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                            />
                            <input
                                type="text"
                                inputMode="numeric"
                                placeholder="حداکثر (مثال: ۵۰۰۰۰۰)"
                                value={filters.max_price}
                                onChange={(e) => {
                                    const converted = persianToEnglish(e.target.value);
                                    setFilters(prev => ({ ...prev, max_price: converted, page: 1 }));
                                }}
                                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-700 dark:text-gray-100"
                            />
                        </div>
                    </div>
                </div>
            </div>

            {/* Products Table */}
            {isLoading ? (
                <ProductsTableSkeleton />
            ) : (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                    {/* Desktop Table */}
                    <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>
                                    </tr>
                                </thead>
                                <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    {products.map((product: Product) => (
                                        <tr key={product.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <div className="flex items-center gap-3">
                                                    <div className="flex-shrink-0">
                                                        {getFirstImageUrl(product) ? (
                                                            <img
                                                                src={getFirstImageUrl(product) as string}
                                                                alt={product.name}
                                                                className="w-10 h-10 object-cover rounded"
                                                            />
                                                        ) : (
                                                            <div className="w-10 h-10 bg-gray-200 dark:bg-gray-600 rounded flex items-center justify-center">
                                                                <Image className="h-5 w-5 text-gray-500" />
                                                            </div>
                                                        )}
                                                    </div>
                                                    <div>
                                                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                                            {product.name}
                                                        </div>
                                                        {product.sku && (
                                                            <div className="text-xs text-gray-500 dark:text-gray-400">
                                                                SKU: {product.sku}
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {formatPrice(product.price || 0)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {product.category?.name || 'بدون دسته‌بندی'}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                {getStatusBadge(product.status || '')}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <div className="flex items-center gap-2">
                                                    <button
                                                        onClick={() => handleView(product.id)}
                                                        className="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
                                                        title="مشاهده"
                                                    >
                                                        <Eye className="h-4 w-4" />
                                                    </button>
                                                    <button
                                                        onClick={() => handleEdit(product.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={() => setDeleteProductId(product.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 Cards */}
                    <div className="md:hidden p-4 space-y-4">
                        {products.map((product: Product) => (
                            <div key={product.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                <div className="flex gap-3 mb-3">
                                    <div className="flex-shrink-0">
                                        {getFirstImageUrl(product) ? (
                                            <img
                                                src={getFirstImageUrl(product) as string}
                                                alt={product.name}
                                                className="w-12 h-12 object-cover rounded"
                                            />
                                        ) : (
                                            <div className="w-12 h-12 bg-gray-200 dark:bg-gray-600 rounded flex items-center justify-center">
                                                <Image className="h-6 w-6 text-gray-500" />
                                            </div>
                                        )}
                                    </div>
                                    <div className="flex-1">
                                        <h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {product.name}
                                        </h3>
                                        <p className="text-sm text-gray-600 dark:text-gray-400">
                                            {formatPrice(product.price || 0)}
                                        </p>
                                        <div className="flex items-center gap-2 mt-1">
                                            {getStatusBadge(product.status || '')}
                                            {product.category && (
                                                <span className="text-xs text-gray-500">
                                                    {product.category.name}
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => handleView(product.id)}
                                        className="flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
                                    >
                                        <Eye className="h-3 w-3" />
                                        مشاهده
                                    </button>
                                    <button
                                        onClick={() => handleEdit(product.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={() => setDeleteProductId(product.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>

                    {/* Empty State */}
                    {(!products || products.length === 0) && !isLoading && (
                        <div className="text-center py-12">
                            <Package className="mx-auto h-12 w-12 text-gray-400" />
                            <h3 className="mt-2 text-sm font-medium text-gray-900 dark:text-gray-100">
                                محصولی موجود نیست
                            </h3>
                            <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                                برای شروع، اولین محصول خود را ایجاد کنید.
                            </p>
                            <div className="mt-6">
                                <Button onClick={handleCreate} className="flex items-center gap-2 mx-auto">
                                    <Plus className="h-4 w-4" />
                                    ایجاد محصول جدید
                                </Button>
                            </div>
                        </div>
                    )}
                </div>
            )}

            {/* Pagination */}
            <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                itemsPerPage={perPage}
                totalItems={total}
                onPageChange={(page) => setFilters(prev => ({ ...prev, page }))}
            />

            {/* Delete Confirmation Modal */}
            <Modal
                isOpen={!!deleteProductId}
                onClose={() => setDeleteProductId(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={() => setDeleteProductId(null)}
                            disabled={isDeleting}
                        >
                            انصراف
                        </Button>
                        <Button
                            variant="danger"
                            onClick={handleDeleteConfirm}
                            loading={isDeleting}
                        >
                            حذف
                        </Button>
                    </div>
                </div>
            </Modal>
        </div>
    );
};

export default ProductsListPage; 