import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useCategories, useDeleteCategory } from '../core/_hooks';
import { Category } from '../core/_models';
import { Button } from "@/components/ui/Button";
import { Plus, FolderOpen, Folder } from "lucide-react";
import { PageContainer } from "../../../components/ui/Typography";
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 { formatDate } from "@/utils/formatters";

const CategoriesListPage = () => {
    const navigate = useNavigate();
    const [deleteCategoryId, setDeleteCategoryId] = useState<string | null>(null);
    const [filters, setFilters] = useState({
        search: ''
    });

    const { data: categories, isLoading, error } = useCategories(filters);
    const { mutate: deleteCategory, isPending: isDeleting } = useDeleteCategory();

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

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

    const handleDeleteConfirm = () => {
        if (deleteCategoryId) {
            deleteCategory(deleteCategoryId, {
                onSuccess: () => {
                    setDeleteCategoryId(null);
                }
            });
        }
    };

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

    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>
        );
    }

    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>
            <PageHeader
                title="مدیریت دسته‌بندی‌ها"
                subtitle="مدیریت دسته‌بندی‌های محصولات"
                icon={FolderOpen}
                actions={createButton}
            />

            <FiltersSection isLoading={isLoading} columns={2}>
                    <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>
            </FiltersSection>

            {isLoading ? (
                <TableSkeleton columns={4} rows={5} />
            ) : (!categories || categories.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={FolderOpen}
                        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>
                                    </tr>
                                </thead>
                                <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    {(categories || []).map((category: Category) => (
                                        <tr key={category.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">
                                                <div className="flex items-center gap-2">
                                                    <Folder className="h-4 w-4 text-amber-500" />
                                                    {category.name}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
                                                <div className="max-w-xs truncate">
                                                    {category.description || 'بدون توضیحات'}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {formatDate(category.created_at)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <ActionButtons
                                                    onEdit={() => handleEdit(category.id)}
                                                    onDelete={() => setDeleteCategoryId(category.id.toString())}
                                                />
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Mobile Cards */}
                    <div className="md:hidden p-4 space-y-4">
                        {(categories || []).map((category: Category) => (
                            <div key={category.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 flex items-center gap-2">
                                            <Folder className="h-4 w-4 text-amber-500" />
                                            {category.name}
                                        </h3>
                                        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                                            {category.description || 'بدون توضیحات'}
                                        </p>
                                    </div>
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                                    تاریخ ایجاد: {formatDate(category.created_at)}
                                </div>
                                <ActionButtons
                                    onEdit={() => handleEdit(category.id)}
                                    onDelete={() => setDeleteCategoryId(category.id.toString())}
                                    showLabels={true}
                                    size="sm"
                                />
                            </div>
                        ))}
                    </div>
                </div>
            )}

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

export default CategoriesListPage; 