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 { PageContainer } from "@/components/ui/Typography";
import { Plus, Package, Image } from "lucide-react";
import { persianToEnglish } from '../../../utils/numberUtils';
import { Pagination } from "@/components/ui/Pagination";
import { PageHeader } from "@/components/layout/PageHeader";
import { FiltersSection } from "@/components/common/FiltersSection";
import { TableSkeleton } from "@/components/common/TableSkeleton";
import { EmptyState } from "@/components/common/EmptyState";
import { DeleteConfirmModal } from "@/components/common/DeleteConfirmModal";
import { ActionButtons } from "@/components/common/ActionButtons";
import { StatusBadge } from "@/components/ui/StatusBadge";
import { formatPrice } from "@/utils/formatters";

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 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 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 (
            <PageContainer>
                <div className="text-center py-12">
                    <p className="text-red-600 dark:text-red-400">خطا در بارگذاری محصولات</p>
                </div>
            </PageContainer>
        );
    }

    const createButton = (
                    <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>
    );

    return (
        <PageContainer>
            <div className="space-y-6">
                <PageHeader
                    title="مدیریت محصولات"
                    subtitle="مدیریت محصولات، قیمت‌ها و موجودی"
                    icon={Package}
                    actions={createButton}
                />

                <FiltersSection isLoading={isLoading} columns={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-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"
                                />
                            </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-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="">همه دسته‌بندی‌ها</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-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="">همه وضعیت‌ها</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-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"
                                    />
                                    <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-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"
                                    />
                                </div>
                            </div>
                </FiltersSection>

                {isLoading ? (
                    <TableSkeleton columns={5} rows={5} />
                ) : products.length === 0 ? (
                    <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                        <EmptyState
                            icon={Package}
                            title="محصولی موجود نیست"
                            description="برای شروع، اولین محصول خود را ایجاد کنید."
                            actionLabel={
                                <>
                                    <Plus className="h-4 w-4" />
                                    ایجاد محصول جدید
                                </>
                            }
                            onAction={handleCreate}
                        />
                    </div>
                ) : (
                    <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">
                                                    <StatusBadge status={product.status || ''} type="product" />
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                    <ActionButtons
                                                        onView={() => handleView(product.id)}
                                                        onEdit={() => handleEdit(product.id)}
                                                        onDelete={() => setDeleteProductId(product.id.toString())}
                                                    />
                                                </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">
                                                <StatusBadge status={product.status || ''} type="product" size="sm" />
                                                {product.category && (
                                                    <span className="text-xs text-gray-500">
                                                        {product.category.name}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                    <ActionButtons
                                        onView={() => handleView(product.id)}
                                        onEdit={() => handleEdit(product.id)}
                                        onDelete={() => setDeleteProductId(product.id.toString())}
                                        showLabels={true}
                                        size="sm"
                                    />
                                </div>
                            ))}
                        </div>
                    </div>
                )}

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

                <DeleteConfirmModal
                    isOpen={!!deleteProductId}
                    onClose={() => setDeleteProductId(null)}
                    onConfirm={handleDeleteConfirm}
                    title="حذف محصول"
                    message="آیا از حذف این محصول اطمینان دارید؟ این عمل قابل بازگشت نیست و تمام اطلاعات مربوط به محصول از جمله نسخه‌ها و تصاویر حذف خواهد شد."
                    isLoading={isDeleting}
                />
            </div>
        </PageContainer>
    );
};

export default ProductsListPage; 