import React, { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Users, Plus, Search, Filter, UserCheck, UserX, Eye, Edit, Trash2, User as UserIcon } from 'lucide-react';
import { useSearchUsers, useUserStats, useVerifyUser, useUnverifyUser, useDeleteUser } from '../core/_hooks';
import { User, UserFilters } from '../core/_models';
import { PageContainer } from '../../../components/ui/Typography';
import { Button } from '../../../components/ui/Button';
import { Input } from '../../../components/ui/Input';
import { Modal } from '../../../components/ui/Modal';
import { Pagination } from '../../../components/ui/Pagination';
import { StatsCard } from '../../../components/dashboard/StatsCard';
import { Table } from '../../../components/ui/Table';
import { TableColumn } from '../../../types';
import { englishToPersian, persianToEnglish } from '../../../utils/numberUtils';
import { PageHeader } from '@/components/layout/PageHeader';
import { FiltersSection } from '@/components/common/FiltersSection';
import { DeleteConfirmModal } from '@/components/common/DeleteConfirmModal';
import { StatusBadge } from '@/components/ui/StatusBadge';

const UsersAdminListPage: React.FC = () => {
    const navigate = useNavigate();

    // State for filters and pagination
    const [filters, setFilters] = useState<UserFilters>({
        limit: 20,
        offset: 0
    });
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedStatus, setSelectedStatus] = useState<'all' | 'verified' | 'unverified'>('all');
    const [deleteModal, setDeleteModal] = useState<{ isOpen: boolean; user: User | null }>({
        isOpen: false,
        user: null
    });
    const [verifyModal, setVerifyModal] = useState<{ isOpen: boolean; user: User | null; action: 'verify' | 'unverify' }>({
        isOpen: false,
        user: null,
        action: 'verify'
    });

    // Hooks
    const { data: searchResult, isLoading, error } = useSearchUsers(filters);
    const users: any[] = searchResult?.users || [];
    const totalMatched: number = searchResult?.total || 0;
    const { data: stats } = useUserStats();
    const verifyUserMutation = useVerifyUser();
    const unverifyUserMutation = useUnverifyUser();
    const deleteUserMutation = useDeleteUser();

    // Handlers
    // Creation disabled per request

    const handleEdit = (user: User) => {
        navigate(`/users-admin/${user.id}/edit`);
    };

    const handleView = (user: User) => {
        navigate(`/users-admin/${user.id}`);
    };

    const handleSearch = () => {
        const newFilters: UserFilters = {
            ...filters,
            offset: 0,
        };

        if (searchTerm.trim()) {
            newFilters.search_text = persianToEnglish(searchTerm.trim());
        } else {
            delete newFilters.search_text;
        }

        if (selectedStatus !== 'all') {
            newFilters.verified = selectedStatus === 'verified';
        } else {
            delete newFilters.verified;
        }

        setFilters(newFilters);
    };

    const handleClearFilters = () => {
        setSearchTerm('');
        setSelectedStatus('all');
        setFilters({
            limit: 20,
            offset: 0
        });
    };

    const handleVerifyToggle = (user: User) => {
        setVerifyModal({ isOpen: true, user, action: user.verified ? 'unverify' : 'verify' });
    };

    const handleVerifyConfirm = () => {
        if (!verifyModal.user) return;
        const user = verifyModal.user;
        if (verifyModal.action === 'unverify') {
            unverifyUserMutation.mutate(user.id.toString(), {
                onSettled: () => setVerifyModal({ isOpen: false, user: null, action: 'verify' })
            });
        } else {
            verifyUserMutation.mutate(user.id.toString(), {
                onSettled: () => setVerifyModal({ isOpen: false, user: null, action: 'verify' })
            });
        }
    };

    const handleDeleteClick = (user: User) => {
        setDeleteModal({ isOpen: true, user });
    };

    const handleDeleteConfirm = () => {
        if (deleteModal.user) {
            deleteUserMutation.mutate(deleteModal.user.id.toString());
            setDeleteModal({ isOpen: false, user: null });
        }
    };

    const handlePageChange = (newOffset: number) => {
        setFilters(prev => ({ ...prev, offset: newOffset }));
    };

    const columns: TableColumn[] = useMemo(() => [
        {
            key: 'name',
            label: 'کاربر',
            align: 'left',
            render: (_val, row: any) => (
                <div className="flex items-center">
                    <div className="flex-shrink-0 h-10 w-10">
                        {row.avatar ? (
                            <img className="h-10 w-10 rounded-full object-cover" src={row.avatar} alt={`${row.first_name} ${row.last_name}`} />
                        ) : (
                            <div className="h-10 w-10 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
                                {row.first_name || row.last_name ? (
                                    <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                        {row.first_name?.charAt(0)}{row.last_name?.charAt(0)}
                                    </span>
                                ) : (
                                    <UserIcon className="h-5 w-5 text-gray-600 dark:text-gray-300" />
                                )}
                            </div>
                        )}
                    </div>
                    <div className="mr-4">
                        <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {row.first_name} {row.last_name}
                        </div>
                        {row.national_code && (
                            <div className="text-sm text-gray-500 dark:text-gray-400">کد ملی: {row.national_code}</div>
                        )}
                    </div>
                </div>
            )
        },
        {
            key: 'phone_number',
            label: 'شماره تلفن',
            align: 'left',
            render: (v: string) => {
                const display = v ? englishToPersian(v) : '-';
                return <span dir="ltr" style={{ direction: 'ltr' }}>{display}</span>;
            }
        },
        { key: 'email', label: 'ایمیل', align: 'left', render: (v: string) => v || '-' },
        {
            key: 'verified',
            label: 'وضعیت',
            align: 'center',
            render: (v: boolean) => <StatusBadge status={v} type="user" />
        },
        {
            key: 'actions',
            label: 'عملیات',
            align: 'center',
            render: (_val, row: any) => (
                <div className="flex items-center gap-2">
                    <button
                        onClick={() => handleView(row)}
                        className="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
                        title="مشاهده جزئیات"
                        data-testid={`view-user-${row.id}`}
                    >
                        <Eye className="h-4 w-4" />
                    </button>
                    <button
                        onClick={() => handleEdit(row)}
                        className="text-indigo-600 hover:text-indigo-900 dark:text-indigo-400 dark:hover:text-indigo-300"
                        title="ویرایش"
                        data-testid={`edit-user-${row.id}`}
                    >
                        <Edit className="h-4 w-4" />
                    </button>
                    <button
                        onClick={() => handleVerifyToggle(row)}
                        className={`${row.verified
                            ? 'text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300'
                            : 'text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300'
                            }`}
                        title={row.verified ? 'لغو تأیید' : 'تأیید کاربر'}
                        data-testid={`verify-user-${row.id}`}
                    >
                        {row.verified ? <UserX className="h-4 w-4" /> : <UserCheck className="h-4 w-4" />}
                    </button>
                    <button
                        onClick={() => handleDeleteClick(row)}
                        className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
                        title="حذف"
                        data-testid={`delete-user-${row.id}`}
                    >
                        <Trash2 className="h-4 w-4" />
                    </button>
                </div>
            )
        }
    ], [handleEdit, handleView, handleVerifyToggle]);

    if (error) {
        return (
            <PageContainer>
                <div className="text-center py-12">
                    <p className="text-red-600">خطا در بارگذاری کاربران</p>
                </div>
            </PageContainer>
        );
    }

    return (
        <PageContainer>
            <div className="space-y-6">
                <PageHeader
                    title="مدیریت کاربران"
                    subtitle="مشاهده و مدیریت کاربران سیستم"
                    icon={Users}
                />

                {/* Stats Cards */}
                {stats && (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <StatsCard
                            title="کل کاربران"
                            value={stats.total_users}
                            icon={Users}
                            color="blue"
                        />
                        <StatsCard
                            title="کاربران تأیید شده"
                            value={stats.verified_users}
                            icon={UserCheck}
                            color="green"
                        />
                        <StatsCard
                            title="کاربران تأیید نشده"
                            value={stats.unverified_users}
                            icon={UserX}
                            color="yellow"
                        />
                        <StatsCard
                            title="ثبت‌نام‌های اخیر"
                            value={stats.recent_registrations}
                            icon={Plus}
                            color="purple"
                        />
                    </div>
                )}

                <FiltersSection isLoading={false} columns={3}>
                        <Input
                            placeholder="جستجو بر اساس نام، شماره تلفن یا ایمیل..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                            data-testid="search-users-input"
                        />
                        <select
                            value={selectedStatus}
                            onChange={(e) => setSelectedStatus(e.target.value as any)}
                            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"
                            data-testid="status-filter-select"
                        >
                            <option value="all">همه کاربران</option>
                            <option value="verified">تأیید شده</option>
                            <option value="unverified">تأیید نشده</option>
                        </select>
                        <div className="flex gap-2">
                            <Button
                                onClick={handleSearch}
                                className="flex items-center gap-2"
                                data-testid="search-button"
                            >
                                <Search className="h-4 w-4" />
                                جستجو
                            </Button>
                            <Button
                                variant="secondary"
                                onClick={handleClearFilters}
                                className="flex items-center gap-2"
                                data-testid="clear-filters-button"
                            >
                                <Filter className="h-4 w-4" />
                                پاک کردن فیلترها
                            </Button>
                        </div>
                </FiltersSection>

                {/* Users Table */}
                <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
                    {isLoading ? (
                        <Table columns={columns} data={[]} loading={true} />
                    ) : users.length === 0 ? (
                        <div className="text-center py-12">
                            <Users className="h-12 w-12 text-gray-400 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">
                                نتیجه‌ای یافت نشد
                            </p>

                        </div>
                    ) : (
                        <Table columns={columns} data={users as any[]} />
                    )}
                </div>

                {/* Pagination */}
                {users.length > 0 && (
                    <Pagination
                        currentPage={Math.floor((filters.offset || 0) / (filters.limit || 20)) + 1}
                        totalPages={Math.ceil((totalMatched || 0) / (filters.limit || 20))}
                        onPageChange={(page) => handlePageChange((page - 1) * (filters.limit || 20))}
                        itemsPerPage={filters.limit || 20}
                        totalItems={totalMatched || users.length}
                    />
                )}

                <DeleteConfirmModal
                    isOpen={deleteModal.isOpen}
                    onClose={() => setDeleteModal({ isOpen: false, user: null })}
                    onConfirm={handleDeleteConfirm}
                    title="حذف کاربر"
                    message={`آیا از حذف کاربر "${deleteModal.user?.first_name} ${deleteModal.user?.last_name}" اطمینان دارید؟`}
                    warningMessage="این عمل غیرقابل بازگشت است."
                    isLoading={deleteUserMutation.isPending}
                />

                {/* Verify/Unverify Confirmation Modal */}
                <Modal
                    isOpen={verifyModal.isOpen}
                    onClose={() => setVerifyModal({ isOpen: false, user: null, action: 'verify' })}
                    title={verifyModal.action === 'unverify' ? 'لغو تأیید کاربر' : 'تأیید کاربر'}
                >
                    <div className="space-y-4">
                        <p className="text-gray-600 dark:text-gray-400">
                            {verifyModal.action === 'unverify'
                                ? `آیا از لغو تأیید «${verifyModal.user?.first_name} ${verifyModal.user?.last_name}» مطمئن هستید؟`
                                : `آیا از تأیید «${verifyModal.user?.first_name} ${verifyModal.user?.last_name}» مطمئن هستید؟`}
                        </p>
                        <div className="flex justify-end gap-3">
                            <Button
                                variant="secondary"
                                onClick={() => setVerifyModal({ isOpen: false, user: null, action: 'verify' })}
                            >
                                انصراف
                            </Button>
                            <Button
                                variant={verifyModal.action === 'unverify' ? 'danger' : 'primary'}
                                onClick={handleVerifyConfirm}
                                loading={verifyUserMutation.isPending || unverifyUserMutation.isPending}
                            >
                                تایید
                            </Button>
                        </div>
                    </div>
                </Modal>
            </div>
        </PageContainer>
    );
};

export default UsersAdminListPage;
