import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { User, Edit, UserCheck, UserX, Trash2, ArrowLeft, Phone, Mail, CreditCard, Calendar } from 'lucide-react';
import { useUser, useVerifyUser, useUnverifyUser, useDeleteUser } from '../core/_hooks';
import { englishToPersian } from '../../../utils/numberUtils';
import { formatDate } from '../../../utils/formatters';
import { PageContainer } from '../../../components/ui/Typography';
import { Button } from '../../../components/ui/Button';
import { Modal } from '../../../components/ui/Modal';

const UserAdminDetailPage: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();

    const [deleteModal, setDeleteModal] = useState(false);

    // Hooks
    const { data: user, isLoading, error } = useUser(id!);
    const verifyUserMutation = useVerifyUser();
    const unverifyUserMutation = useUnverifyUser();
    const deleteUserMutation = useDeleteUser();

    // Handlers
    const handleEdit = () => {
        navigate(`/users-admin/${id}/edit`);
    };

    const handleVerifyToggle = () => {
        if (!user) return;

        if (user.verified) {
            unverifyUserMutation.mutate(user.id.toString());
        } else {
            verifyUserMutation.mutate(user.id.toString());
        }
    };

    const handleDeleteClick = () => {
        setDeleteModal(true);
    };

    const handleDeleteConfirm = () => {
        if (user) {
            deleteUserMutation.mutate(user.id.toString(), {
                onSuccess: () => {
                    navigate('/users-admin');
                }
            });
        }
    };

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

    if (isLoading) {
        return (
            <PageContainer>
                <div className="space-y-6 animate-pulse">
                    <div className="flex items-center justify-between">
                        <div className="h-8 bg-gray-200 dark:bg-gray-700 rounded w-48"></div>
                        <div className="h-10 bg-gray-200 dark:bg-gray-700 rounded w-24"></div>
                    </div>
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <div className="lg:col-span-2 space-y-6">
                            {[...Array(3)].map((_, i) => (
                                <div key={i} className="card p-6">
                                    <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-32 mb-4"></div>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        {[...Array(4)].map((_, j) => (
                                            <div key={j}>
                                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-20 mb-2"></div>
                                                <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32"></div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="space-y-6">
                            {[...Array(2)].map((_, i) => (
                                <div key={i} className="card p-6">
                                    <div className="h-6 bg-gray-200 dark:bg-gray-700 rounded w-24 mb-4"></div>
                                    <div className="space-y-3">
                                        {[...Array(3)].map((_, j) => (
                                            <div key={j} className="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </PageContainer>
        );
    }

    if (error || !user) {
        return (
            <PageContainer>
                <div className="text-center py-12">
                    <p className="text-red-600">خطا در بارگذاری اطلاعات کاربر</p>
                    <Button onClick={handleBack} className="mt-4">
                        بازگشت به لیست کاربران
                    </Button>
                </div>
            </PageContainer>
        );
    }

    return (
        <PageContainer>
            <div className="space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <Button
                            variant="secondary"
                            onClick={handleBack}
                            className="flex items-center gap-2"
                            data-testid="back-button"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            بازگشت
                        </Button>
                        <div>
                            <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                جزئیات کاربر
                            </h1>
                            <p className="text-gray-600 dark:text-gray-400">
                                مشاهده و مدیریت اطلاعات کاربر
                            </p>
                        </div>
                    </div>
                    <div className="flex items-center gap-3">
                        <Button
                            onClick={handleEdit}
                            className="flex items-center gap-2"
                            data-testid="edit-user-button"
                        >
                            <Edit className="h-4 w-4" />
                            ویرایش
                        </Button>
                        <Button
                            variant={user.verified ? "secondary" : "primary"}
                            onClick={() => setDeleteModal(true)}
                            loading={verifyUserMutation.isPending || unverifyUserMutation.isPending}
                            className="flex items-center gap-2"
                            data-testid="verify-toggle-button"
                        >
                            {user.verified ? (
                                <>
                                    <UserX className="h-4 w-4" />
                                    لغو تأیید
                                </>
                            ) : (
                                <>
                                    <UserCheck className="h-4 w-4" />
                                    تأیید کاربر
                                </>
                            )}
                        </Button>
                        <Button
                            variant="danger"
                            onClick={handleDeleteClick}
                            className="flex items-center gap-2"
                            data-testid="delete-user-button"
                        >
                            <Trash2 className="h-4 w-4" />
                            حذف
                        </Button>
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* User Profile Card */}
                    <div className="lg:col-span-1">
                        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg p-6">
                            <div className="text-center">
                                <div className="mx-auto h-24 w-24 mb-4">
                                    {user.avatar ? (
                                        <img
                                            className="h-24 w-24 rounded-full object-cover mx-auto"
                                            src={user.avatar}
                                            alt={`${user.first_name} ${user.last_name}`}
                                        />
                                    ) : (
                                        <div className="h-24 w-24 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center mx-auto">
                                            <span className="text-2xl font-bold text-gray-700 dark:text-gray-300">
                                                {user.first_name.charAt(0)}{user.last_name.charAt(0)}
                                            </span>
                                        </div>
                                    )}
                                </div>
                                <h2 className="text-xl font-bold text-gray-900 dark:text-gray-100 mb-1">
                                    {user.first_name} {user.last_name}
                                </h2>
                                <div className="flex justify-center mb-4">
                                    <span
                                        className={`inline-flex px-3 py-1 text-sm font-semibold rounded-full ${user.verified
                                            ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                                            : 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
                                            }`}
                                    >
                                        {user.verified ? 'تأیید شده' : 'تأیید نشده'}
                                    </span>
                                </div>
                                <p className="text-gray-600 dark:text-gray-400 text-sm">
                                    شناسه کاربر: {user.id}
                                </p>
                            </div>
                        </div>
                    </div>

                    {/* User Details */}
                    <div className="lg:col-span-2">
                        <div className="bg-white dark:bg-gray-800 shadow-sm border border-gray-200 dark:border-gray-700 rounded-lg">
                            <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                                <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2">
                                    <User className="h-5 w-5" />
                                    اطلاعات شخصی
                                </h3>
                            </div>
                            <div className="p-6">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div className="space-y-4">
                                        <div className="flex items-center gap-3">
                                            <Phone className="h-5 w-5 text-gray-400" />
                                            <div>
                                                <p className="text-sm font-medium text-gray-500 dark:text-gray-400">شماره تلفن</p>
                                                <p className="text-gray-900 dark:text-gray-100" dir="ltr" style={{ direction: 'ltr' }}>{englishToPersian(user.phone_number)}</p>
                                            </div>
                                        </div>

                                        {user.email && (
                                            <div className="flex items-center gap-3">
                                                <Mail className="h-5 w-5 text-gray-400" />
                                                <div>
                                                    <p className="text-sm font-medium text-gray-500 dark:text-gray-400">ایمیل</p>
                                                    <p className="text-gray-900 dark:text-gray-100">{user.email}</p>
                                                </div>
                                            </div>
                                        )}

                                        {user.national_code && (
                                            <div className="flex items-center gap-3">
                                                <CreditCard className="h-5 w-5 text-gray-400" />
                                                <div>
                                                    <p className="text-sm font-medium text-gray-500 dark:text-gray-400">کد ملی</p>
                                                    <p className="text-gray-900 dark:text-gray-100">{user.national_code}</p>
                                                </div>
                                            </div>
                                        )}
                                    </div>

                                    <div className="space-y-4">
                                        {user.created_at && (
                                            <div className="flex items-center gap-3">
                                                <Calendar className="h-5 w-5 text-gray-400" />
                                                <div>
                                                    <p className="text-sm font-medium text-gray-500 dark:text-gray-400">تاریخ ثبت‌نام</p>
                                                    <p className="text-gray-900 dark:text-gray-100">
                                                        {formatDate(user.created_at)}
                                                    </p>
                                                </div>
                                            </div>
                                        )}

                                        {user.updated_at && (
                                            <div className="flex items-center gap-3">
                                                <Calendar className="h-5 w-5 text-gray-400" />
                                                <div>
                                                    <p className="text-sm font-medium text-gray-500 dark:text-gray-400">آخرین به‌روزرسانی</p>
                                                    <p className="text-gray-900 dark:text-gray-100">
                                                        {formatDate(user.updated_at)}
                                                    </p>
                                                </div>
                                            </div>
                                        )}

                                        <div className="flex items-center gap-3">
                                            <UserCheck className="h-5 w-5 text-gray-400" />
                                            <div>
                                                <p className="text-sm font-medium text-gray-500 dark:text-gray-400">وضعیت حساب</p>
                                                <p className={`font-medium ${user.verified
                                                    ? 'text-green-600 dark:text-green-400'
                                                    : 'text-yellow-600 dark:text-yellow-400'
                                                    }`}>
                                                    {user.verified ? 'حساب تأیید شده است' : 'حساب تأیید نشده است'}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>



                {/* Delete Confirmation Modal */}
                <Modal
                    isOpen={deleteModal}
                    onClose={() => setDeleteModal(false)}
                    title={user.verified ? 'لغو تأیید کاربر' : 'تأیید کاربر'}
                >
                    <div className="space-y-4">
                        <p className="text-gray-600 dark:text-gray-400">
                            {user.verified ? `آیا از لغو تأیید «${user.first_name} ${user.last_name}» مطمئن هستید؟` : `آیا از تأیید «${user.first_name} ${user.last_name}» مطمئن هستید؟`}
                        </p>
                        <div className="flex justify-end gap-3">
                            <Button
                                variant="secondary"
                                onClick={() => setDeleteModal(false)}
                                data-testid="cancel-delete-button"
                            >
                                انصراف
                            </Button>
                            <Button
                                variant={user.verified ? 'danger' : 'primary'}
                                onClick={() => {
                                    handleVerifyToggle();
                                    setDeleteModal(false);
                                }}
                                loading={verifyUserMutation.isPending || unverifyUserMutation.isPending}
                            >
                                تایید
                            </Button>
                        </div>
                    </div>
                </Modal>
            </div>
        </PageContainer>
    );
};

export default UserAdminDetailPage;
