import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useRoles, useDeleteRole } from '../core/_hooks';
import { Role } from '@/types/auth';
import { Button } from "@/components/ui/Button";

import { Trash2, Edit3, Plus, UserCog, Shield, Eye, Settings } from "lucide-react";
import { Modal } from "@/components/ui/Modal";
import { PageContainer, PageTitle, SectionSubtitle } from '../../../components/ui/Typography';

// Skeleton Loading Component
const RolesTableSkeleton = () => (
    <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
        {/* Desktop Table Skeleton */}
        <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((_, index) => (
                            <tr key={index} className="animate-pulse">
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-300 dark:bg-gray-600 rounded w-32"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-300 dark:bg-gray-600 rounded w-48"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="h-4 bg-gray-300 dark:bg-gray-600 rounded w-20"></div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                    <div className="flex gap-2">
                                        <div className="h-8 w-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
                                        <div className="h-8 w-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
                                        <div className="h-8 w-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>

        {/* Mobile Cards Skeleton */}
        <div className="md:hidden p-4 space-y-4">
            {[...Array(3)].map((_, index) => (
                <div key={index} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 animate-pulse">
                    <div className="space-y-3">
                        <div className="h-5 bg-gray-300 dark:bg-gray-600 rounded w-3/4"></div>
                        <div className="h-4 bg-gray-300 dark:bg-gray-600 rounded w-full"></div>
                        <div className="h-3 bg-gray-300 dark:bg-gray-600 rounded w-1/3"></div>
                        <div className="flex gap-2 pt-2">
                            <div className="h-8 w-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
                            <div className="h-8 w-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
                            <div className="h-8 w-8 bg-gray-300 dark:bg-gray-600 rounded"></div>
                        </div>
                    </div>
                </div>
            ))}
        </div>
    </div>
);

const RolesListPage = () => {
    const navigate = useNavigate();
    const [deleteRoleId, setDeleteRoleId] = useState<string | null>(null);
    const [filters, setFilters] = useState({
        search: ''
    });

    const { data: roles, isLoading, error } = useRoles(filters);
    const { mutate: deleteRole, isPending: isDeleting } = useDeleteRole();

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

    const handleView = (roleId: number) => {
        navigate(`/roles/${roleId}`);
    };

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

    const handlePermissions = (roleId: number) => {
        navigate(`/roles/${roleId}/permissions`);
    };

    const handleDeleteConfirm = () => {
        if (deleteRoleId) {
            deleteRole(deleteRoleId, {
                onSuccess: () => {
                    setDeleteRoleId(null);
                }
            });
        }
    };

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

    const handleDelete = (roleId: number) => {
        setDeleteRoleId(roleId.toString());
    };

    const cancelDelete = () => {
        setDeleteRoleId(null);
    };

    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 (
        <PageContainer>
            {/* Header */}
            <div className="flex flex-col space-y-3 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
                <div>
                    <div className="flex items-center gap-2 mb-2">
                        <UserCog className="h-6 w-6" />
                        <PageTitle>مدیریت نقش‌ها</PageTitle>
                    </div>
                    <p className="text-gray-600 dark:text-gray-400">مدیریت نقش‌ها و دسترسی‌های سیستم</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>

            {/* Roles Table */}
            {isLoading ? (
                <RolesTableSkeleton />
            ) : (roles || []).length === 0 ? (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                    <div className="text-center py-12">
                        <UserCog className="h-12 w-12 text-gray-400 dark:text-gray-500 mx-auto mb-4" />
                        <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
                            هیچ نقش یافت نشد
                        </h3>
                        <p className="text-gray-600 dark:text-gray-400 mb-4">
                            {filters.search
                                ? "نتیجه‌ای برای جستجوی شما یافت نشد"
                                : "شما هنوز هیچ نقش ایجاد نکرده‌اید"
                            }
                        </p>
                        <Button onClick={handleCreate} className="flex items-center gap-2">
                            <Plus className="h-4 w-4 ml-2" />
                            اولین نقش را ایجاد کنید
                        </Button>
                    </div>
                </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">
                                    {(roles || []).map((role: Role) => (
                                        <tr key={role.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {role.title}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {role.description}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {new Date(role.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={() => handleView(role.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(role.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={() => handlePermissions(role.id)}
                                                        className="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300"
                                                        title="مدیریت دسترسی‌ها"
                                                    >
                                                        <Settings className="h-4 w-4" />
                                                    </button>
                                                    <button
                                                        onClick={() => setDeleteRoleId(role.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">
                        {(roles || []).map((role: Role) => (
                            <div key={role.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
                                <div className="flex justify-between items-start mb-2">
                                    <div>
                                        <h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                            {role.title}
                                        </h3>
                                        <p className="text-sm text-gray-600 dark:text-gray-400">
                                            {role.description}
                                        </p>
                                    </div>
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                                    تاریخ ایجاد: {new Date(role.created_at).toLocaleDateString('fa-IR')}
                                </div>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => handleView(role.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(role.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={() => handlePermissions(role.id)}
                                        className="flex items-center gap-1 px-2 py-1 text-xs text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300"
                                    >
                                        <Settings className="h-3 w-3" />
                                        دسترسی‌ها
                                    </button>
                                    <button
                                        onClick={() => setDeleteRoleId(role.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>
                </div>
            )}

            {/* Delete Confirmation Modal */}
            <Modal
                isOpen={!!deleteRoleId}
                onClose={cancelDelete}
                title="تأیید حذف"
                size="sm"
            >
                <div className="space-y-4">
                    <p className="text-gray-600 dark:text-gray-300">
                        آیا از حذف این نقش اطمینان دارید؟ این عمل قابل بازگشت نیست.
                    </p>
                    <div className="flex justify-end gap-3">
                        <Button variant="secondary" onClick={cancelDelete}>
                            انصراف
                        </Button>
                        <Button
                            variant="danger"
                            onClick={handleDeleteConfirm}
                            loading={isDeleting}
                        >
                            حذف
                        </Button>
                    </div>
                </div>
            </Modal>
        </PageContainer>
    );
};

export default RolesListPage; 