import { type FC, useState } from 'react'
import { useGetCoupons, useDeleteCoupon } from './hooks/useCouponData'
import { type CouponResponseData } from './types/Types'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'
import PaginationUi from '@/components/PaginationUi'
import Td from '@/components/Td'
import TrashWithConfrim from '@/components/TrashWithConfrim'
import { Edit } from 'iconsax-react'
import Button from '@/components/Button'
import { Link } from 'react-router-dom'
import { Pages } from '@/config/Pages'
import { useNavigate } from 'react-router-dom'

const CouponList: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const { data: couponsData, isLoading, error, refetch } = useGetCoupons(currentPage)
    const deleteCouponMutation = useDeleteCoupon();
    const navigate = useNavigate();

    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 handleDeleteCoupon = async (couponId: string) => {
        await deleteCouponMutation.mutateAsync(couponId);
        refetch()
    };

    const coupons = couponsData?.results?.coupons || [];
    const pager = couponsData?.results?.pager;

    return (
        <div>
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن کوپن'
                    onClick={() => navigate(`${Pages.coupon.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={'وضعیت'} />
                            <Td text={'تاریخ انقضا'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {coupons.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={9} className="text-center py-8 text-gray-500">
                                    هیچ کوپنی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            coupons.map((coupon: CouponResponseData) => (
                                <tr key={coupon._id} className='tr'>
                                    <Td text={coupon.code} />
                                    <Td text={coupon.discountPercentage ? `${coupon.discountPercentage}%` : '-'} />
                                    <Td text={coupon.discountAmount ? `${coupon.discountAmount.toLocaleString('fa-IR')} تومان` : '-'} />
                                    <Td text={coupon.usageLimit.toLocaleString('fa-IR')} />
                                    <Td text={coupon.usageCount.toLocaleString('fa-IR')} />
                                    <Td text={coupon.minPurchaseAmount ? `${coupon.minPurchaseAmount.toLocaleString('fa-IR')} تومان` : '-'} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <span className={`px-2 py-1 rounded-full text-xs ${coupon.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                                                {coupon.isActive ? 'فعال' : 'غیرفعال'}
                                            </span>
                                        </div>
                                    </Td>
                                    <Td text={coupon.expirationDate} />
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Link to={`${Pages.coupon.detail}${coupon._id}`}>
                                                <Edit color='#8C90A3' size={16} className="cursor-pointer hover:text-blue-500" />
                                            </Link>

                                            <TrashWithConfrim
                                                onDelete={() => handleDeleteCoupon(coupon._id)}
                                                isLoading={deleteCouponMutation.isPending}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

export default CouponList