import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useProductOptions, useDeleteProductOption } from '../core/_hooks';
import { ProductOption } from '../core/_models';
import { Button } from "@/components/ui/Button";

import { Trash2, Edit3, Plus, Settings, Tag } from "lucide-react";
import { Modal } from "@/components/ui/Modal";

const ProductOptionsTableSkeleton = () => (
    <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>
                        </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="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 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">
            {/* 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">
                        <Settings 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-2 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>
            </div>

            {/* Product Options Table */}
            {isLoading ? (
                <ProductOptionsTableSkeleton />
            ) : (
                <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">
                                                {new Date(option.created_at).toLocaleDateString('fa-IR')}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <div className="flex items-center gap-2">
                                                    <button
                                                        onClick={() => handleEdit(option.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={() => setDeleteOptionId(option.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">
                        {(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">
                                    تاریخ ایجاد: {new Date(option.created_at).toLocaleDateString('fa-IR')}
                                </div>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => handleEdit(option.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={() => setDeleteOptionId(option.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 */}
                    {(!productOptions || productOptions.length === 0) && !isLoading && (
                        <div className="text-center py-12">
                            <Settings 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>
            )}

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

export default ProductOptionsListPage; 