import { type FC, useState } from 'react'
import { useGetShipment, useDeleteShipment } from './hooks/useShipmentData'
import { type Shipper } from './types/Types'
import PageLoading from '@/components/PageLoading';
import Error from '@/components/Error';
import Button from '@/components/Button';
import PaginationUi from '@/components/PaginationUi';
import Td from '@/components/Td';
import TrashWithConfrim from '@/components/TrashWithConfrim';
import { Edit } from 'iconsax-react';
import { Link } from 'react-router-dom';
import { Pages } from '@/config/Pages';
import { useNavigate } from 'react-router-dom';

const ShippingList: FC = () => {
    const [currentPage, setCurrentPage] = useState(1);
    const navigate = useNavigate();
    const { data, isLoading, error, refetch } = useGetShipment(currentPage);
    const deleteShipmentMutation = useDeleteShipment();

    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 handleDeleteShipment = async (shipmentId: string) => {
        await deleteShipmentMutation.mutateAsync(shipmentId);
        refetch();
    };

    const shipments = data?.results?.shipper || [];
    const pager = data?.results?.pager;

    const getDeliveryTypeText = (type: string) => {
        switch (type) {
            case 'Standard':
                return 'معمولی';
            case 'SameDay':
                return 'همان روز';
            case 'Express':
                return 'اکسپرس';
            default:
                return type;
        }
    };

    return (
        <div>
            <div className='flex justify-end mt-5'>
                <Button
                    label='افزودن روش ارسال'
                    onClick={() => navigate(`${Pages.shipment.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={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {shipments.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={7} className="text-center py-8 text-gray-500">
                                    هیچ روش ارسالی یافت نشد
                                </td>
                            </tr>
                        ) : (
                            shipments.map((shipment: Shipper) => (
                                <tr key={shipment._id} className='tr'>
                                    <Td text={shipment.name} />
                                    <Td text={shipment.description} />
                                    <Td text={getDeliveryTypeText(shipment.deliveryType)} />
                                    <Td text={shipment.deliveryTime.toString()} />
                                    <Td text="">
                                        <div className="text-sm">
                                            {shipment.costs.length > 0 ? (
                                                <div>
                                                    {shipment.costs.slice(0, 2).map((cost, index) => (
                                                        <div key={index} className="mb-1">
                                                            {cost.weightRange.min}-{cost.weightRange.max}kg:
                                                            {cost.cost_first}/{cost.cost_rest}
                                                        </div>
                                                    ))}
                                                    {shipment.costs.length > 2 && (
                                                        <span className="text-gray-500">و {shipment.costs.length - 2} مورد دیگر...</span>
                                                    )}
                                                </div>
                                            ) : (
                                                'بدون هزینه'
                                            )}
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Link to={`${Pages.shipment.update}${shipment._id}`}>
                                                <Edit color='#8C90A3' size={16} className="cursor-pointer hover:text-blue-500" />
                                            </Link>

                                            <TrashWithConfrim
                                                onDelete={() => handleDeleteShipment(shipment._id.toString())}
                                                isLoading={deleteShipmentMutation.isPending}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

export default ShippingList