import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useProductOptions, useDeleteProductOption } from '../core/_hooks';
import { ProductOption } from '../core/_models';
import { Settings, Tag, Plus } from "lucide-react";
import { TableSkeleton } from '@/components/common/TableSkeleton';
import { PageHeader } from '@/components/layout/PageHeader';
import { EmptyState } from '@/components/common/EmptyState';
import { ActionButtons } from '@/components/common/ActionButtons';
import { DeleteConfirmModal } from '@/components/common/DeleteConfirmModal';
import { FiltersSection } from '@/components/common/FiltersSection';
import { formatDate } from '@/utils/formatters';

const ProductOptionsListPage = () => {
    const navigate = useNavigate();
    const [deleteOptionId, setDeleteOptionId] = useState<string | null>(null);
    const [filters, setFilters] = useState({
        search: ''
    });

    const { data: productOptions, isLoading, error } = useProductOptions(filters);
    const { mutate: deleteOption, isPending: isDeleting } = useDeleteProductOption();

    const handleCreate = () => {
        navigate('/product-options/create');
    };

    const handleEdit = (optionId: number) => {
        navigate(`/product-options/${optionId}/edit`);
    };

    const handleDeleteConfirm = () => {
        if (deleteOptionId) {
            deleteOption(deleteOptionId, {
                onSuccess: () => {
                    setDeleteOptionId(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>
        );
    }

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title="مدیریت گزینه‌های محصول"
                subtitle="تنظیمات گزینه‌های قابل انتخاب برای محصولات"
                icon={Settings}
                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>
                }
            />

            <FiltersSection>
                    <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>

            {/* Product Options Table */}
            {isLoading ? (
                <TableSkeleton columns={4} rows={5} />
            ) : (
                <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">
                                    {(productOptions || []).map((option: ProductOption) => (
                                        <tr key={option.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">
                                                {option.title}
                                            </td>
                                            <td className="px-6 py-4 text-sm text-gray-900 dark:text-gray-100">
                                                <div className="flex flex-wrap gap-1 max-w-xs">
                                                    {(option.options || []).slice(0, 3).map((optionItem, index) => (
                                                        <span
                                                            key={index}
                                                            className="inline-flex items-center px-2 py-1 rounded-md text-xs bg-gray-100 dark:bg-gray-600 text-gray-800 dark:text-gray-200"
                                                        >
                                                            <Tag className="h-3 w-3 mr-1" />
                                                            {optionItem.title}
                                                        </span>
                                                    ))}
                                                    {(option.options || []).length > 3 && (
                                                        <span className="inline-flex items-center px-2 py-1 rounded-md text-xs bg-primary-100 dark:bg-primary-900 text-primary-800 dark:text-primary-200">
                                                            +{(option.options || []).length - 3} بیشتر
                                                        </span>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {formatDate(option.created_at)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <ActionButtons
                                                    onEdit={() => handleEdit(option.id)}
                                                    onDelete={() => setDeleteOptionId(option.id.toString())}
                                                />
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Mobile Cards */}
                    <div className="md:hidden p-4 space-y-4">
                        {(productOptions || []).map((option: ProductOption) => (
                            <div key={option.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">
                                            {option.title}
                                        </h3>
                                        <div className="flex flex-wrap gap-1 mt-2">
                                            {(option.options || []).slice(0, 3).map((optionItem, index) => (
                                                <span
                                                    key={index}
                                                    className="inline-flex items-center px-2 py-1 rounded-md text-xs bg-gray-100 dark:bg-gray-600 text-gray-800 dark:text-gray-200"
                                                >
                                                    <Tag className="h-3 w-3 mr-1" />
                                                    {optionItem.title}
                                                </span>
                                            ))}
                                            {(option.options || []).length > 3 && (
                                                <span className="inline-flex items-center px-2 py-1 rounded-md text-xs bg-primary-100 dark:bg-primary-900 text-primary-800 dark:text-primary-200">
                                                    +{(option.options || []).length - 3} بیشتر
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                                    تاریخ ایجاد: {formatDate(option.created_at)}
                                </div>
                                <ActionButtons
                                    onEdit={() => handleEdit(option.id)}
                                    onDelete={() => setDeleteOptionId(option.id.toString())}
                                />
                            </div>
                        ))}
                    </div>
                </div>
            )}

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

export default ProductOptionsListPage; 