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 { Plus, Shield, Eye, Settings } 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 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>
        );
    }

    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={Shield}
                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} />
            ) : (roles || []).length === 0 ? (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                    <EmptyState
                        icon={Shield}
                        title="هیچ نقش یافت نشد"
                        description={filters.search
                                ? "نتیجه‌ای برای جستجوی شما یافت نشد"
                            : "شما هنوز هیچ نقش ایجاد نکرده‌اید"}
                        actionLabel={
                            <>
                            <Plus className="h-4 w-4 ml-2" />
                            اولین نقش را ایجاد کنید
                            </>
                        }
                        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">
                                    {(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">
                                                {formatDate(role.created_at)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <div className="flex items-center gap-2">
                                                    <ActionButtons
                                                        onView={() => handleView(role.id)}
                                                        onEdit={() => handleEdit(role.id)}
                                                        onDelete={() => setDeleteRoleId(role.id.toString())}
                                                    />
                                                    <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>
                                                </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">
                                    تاریخ ایجاد: {formatDate(role.created_at)}
                                </div>
                                <div className="flex items-center gap-2">
                                    <ActionButtons
                                        onView={() => handleView(role.id)}
                                        onEdit={() => handleEdit(role.id)}
                                        onDelete={() => setDeleteRoleId(role.id.toString())}
                                        showLabels={true}
                                        size="sm"
                                    />
                                    <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>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <DeleteConfirmModal
                isOpen={!!deleteRoleId}
                onClose={cancelDelete}
                onConfirm={handleDeleteConfirm}
                title="تأیید حذف"
                message="آیا از حذف این نقش اطمینان دارید؟ این عمل قابل بازگشت نیست."
                isLoading={isDeleting}
            />
        </PageContainer>
    );
};

export default RolesListPage; 