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

import { Users, UserPlus, Plus } from "lucide-react";
import { PageContainer, SectionSubtitle } from '../../../components/ui/Typography';
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 { formatDate } from '@/utils/formatters';

const AdminUsersListPage = () => {
    const navigate = useNavigate();
    const [deleteUserId, setDeleteUserId] = useState<string | null>(null);
    const [filters, setFilters] = useState({
        search: '',
        status: ''
    });

    const { data: users, isLoading, error } = useAdminUsers(filters);
    const { mutate: deleteUser, isPending: isDeleting } = useDeleteAdminUser();

    const handleCreate = () => {
        navigate('/admin-users/create');
    };

    const handleView = (userId: number) => {
        navigate(`/admin-users/${userId}`);
    };

    const handleEdit = (userId: number) => {
        navigate(`/admin-users/${userId}/edit`);
    };

    const handleDeleteConfirm = () => {
        if (deleteUserId) {
            deleteUser(deleteUserId, {
                onSuccess: () => {
                    setDeleteUserId(null);
                }
            });
        }
    };

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

    const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setFilters(prev => ({ ...prev, status: 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 (
        <PageContainer>
            <PageHeader
                title="مدیریت کاربران ادمین"
                subtitle="مدیریت کاربران دسترسی به پنل ادمین"
                icon={Users}
                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>
                }
            />

            {/* Filters */}
            <SectionSubtitle>فیلترها</SectionSubtitle>
            <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>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            وضعیت
                        </label>
                        <select
                            value={filters.status}
                            onChange={handleStatusChange}
                            className="w-full px-3 py-3 text-base border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:text-gray-100 transition-all duration-200"
                        >
                            <option value="">همه</option>
                            <option value="active">فعال</option>
                            <option value="deactive">غیرفعال</option>
                        </select>
                    </div>
                </div>
            </div>

            {/* Users Table */}
            {isLoading ? (
                <TableSkeleton columns={5} rows={5} />
            ) : (users || []).length === 0 ? (
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                    <EmptyState
                        icon={Users}
                        title="هیچ کاربر ادمین یافت نشد"
                        description={filters.search || filters.status
                            ? "نتیجه‌ای برای جستجوی شما یافت نشد"
                            : "شما هنوز هیچ کاربر ادمین ایجاد نکرده‌اید"
                        }
                        actionLabel={
                            <>
                                <UserPlus 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>
                                        <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">
                                    {(users || []).map((user: AdminUserInfo) => (
                                        <tr key={user.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">
                                                {user.first_name} {user.last_name}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {user.username}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${user.status === 'active'
                                                    ? 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100'
                                                    : 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100'
                                                    }`}>
                                                    {user.status === 'active' ? 'فعال' : 'غیرفعال'}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                                                {formatDate(user.created_at)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <ActionButtons
                                                    onView={() => handleView(user.id)}
                                                    onEdit={() => handleEdit(user.id)}
                                                    onDelete={() => setDeleteUserId(user.id.toString())}
                                                />
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>

                    {/* Mobile Cards */}
                    <div className="md:hidden p-4 space-y-4">
                        {(users || []).map((user: AdminUserInfo) => (
                            <div key={user.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">
                                            {user.first_name} {user.last_name}
                                        </h3>
                                        <p className="text-sm text-gray-600 dark:text-gray-400">
                                            {user.username}
                                        </p>
                                    </div>
                                    <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${user.status === 'active'
                                        ? 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100'
                                        : 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100'
                                        }`}>
                                        {user.status === 'active' ? 'فعال' : 'غیرفعال'}
                                    </span>
                                </div>
                                <div className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                                    تاریخ ایجاد: {formatDate(user.created_at)}
                                </div>
                                <ActionButtons
                                    onView={() => handleView(user.id)}
                                    onEdit={() => handleEdit(user.id)}
                                    onDelete={() => setDeleteUserId(user.id.toString())}
                                />
                            </div>
                        ))}
                    </div>
                </div>
            )}

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

export default AdminUsersListPage; 