import { type FC, useState } from 'react'
import { useDeleteAdmin, useGetAdmins } from './hooks/useAdminData'
import { useQueryClient } from '@tanstack/react-query'
import { type Admin } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import PaginationUi from '../../components/PaginationUi'
import Td from '../../components/Td'
import { Calendar, Call, Card, User as UserIcon } from 'iconsax-react'
import Button from '@/components/Button'
import { useNavigate } from 'react-router-dom'
import { Pages } from '@/config/Pages'
import TrashWithConfrim from '../../components/TrashWithConfrim'

const List: FC = () => {

    const navigate = useNavigate();
    const queryClient = useQueryClient();
    const [currentPage, setCurrentPage] = useState(1);
    const { data: adminsData, isLoading, error } = useGetAdmins(currentPage);
    const deleteAdminMutation = useDeleteAdmin();

    if (isLoading) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <PageLoading />
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex justify-center items-center min-h-[400px]">
                <Error errorText="خطا در بارگذاری ادمین‌ها" />
            </div>
        );
    }

    const admins = adminsData?.results?.admins || [];
    const pager = adminsData?.results?.pager;

    const formatDate = (dateString: string) => {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleDateString('fa-IR');
    };

    return (
        <div>
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن ادمین'
                    onClick={() => navigate(`${Pages.admin.create}`)}
                    className='w-fit'
                />
            </div>
            <div className='relative overflow-x-auto rounded-3xl mt-5 w-full'>
                <table className='w-full text-sm'>
                    <thead className='thead'>
                        <tr>
                            <Td text={'نام و نام خانوادگی'} />
                            <Td text={'نام کاربری'} />
                            <Td text={'ایمیل'} />
                            <Td text={'شماره تلفن'} />
                            <Td text={'نقش'} />
                            <Td text={'تاریخ ایجاد'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {admins.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className="text-center py-8 text-gray-500">
                                    هیچ ادمینی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            admins.map((admin: Admin) => (
                                <tr key={admin._id} className='tr'>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <UserIcon size={16} color="#8C90A3" />
                                            <span>{admin.fullName || '-'}</span>
                                        </div>
                                    </Td>
                                    <Td text={admin.userName} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Card size={16} color="#8C90A3" />
                                            <span>{admin.email}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Call size={16} color="#8C90A3" />
                                            <span>{admin.phoneNumber}</span>
                                        </div>
                                    </Td>
                                    <Td text={admin.role?.name || '-'} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Calendar size={16} color="#8C90A3" />
                                            <span>{formatDate(admin.createdAt)}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">

                                            <TrashWithConfrim
                                                onDelete={() => {
                                                    deleteAdminMutation.mutate(admin._id, {
                                                        onSuccess: () => {
                                                            queryClient.invalidateQueries({ queryKey: ['admins'] })
                                                        }
                                                    })
                                                }}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <PaginationUi
                pager={pager}
                onPageChange={(page) => {
                    setCurrentPage(page);
                }}
            />
        </div>
    )
}

export default List