import { type FC, useState } from 'react'
import { useGetPricing, useDeletePricing } from './hooks/useSettingData'
import { type PricingItem } from './types/Types'
import PageLoading from '../../components/PageLoading'
import Error from '../../components/Error'
import Td from '../../components/Td'
import Button from '../../components/Button'
import AddPricingModal from './components/AddPrcingModal'
import EditPricingModal from './components/EditPricingModal'
import TrashWithConfrim from '../../components/TrashWithConfrim'
import { Edit } from 'iconsax-react'
import { toast } from 'react-toastify'

const Pricing: FC = () => {
    const { data, isLoading, error } = useGetPricing();
    const deletePricingMutation = useDeletePricing();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [selectedPricingItem, setSelectedPricingItem] = useState<PricingItem | null>(null);

    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 pricingItems = data?.results?.pricing || [];

    const handleEditPricing = (pricingItem: PricingItem) => {
        setSelectedPricingItem(pricingItem);
        setIsEditModalOpen(true);
    };

    const handleDeletePricing = async (id: string) => {
        try {
            await deletePricingMutation.mutateAsync(id);
            toast.success('قیمت‌گذاری با موفقیت حذف شد');
        } catch (error) {
            const message = (error as { response?: { data?: { message?: string } } })?.response?.data?.message || 'خطا در حذف قیمت‌گذاری';
            toast.error(message);
        }
    };

    return (
        <div>
            <div className="flex justify-between items-center mb-6">
                <h1 className="">مدیریت قیمت‌گذاری</h1>
                <Button
                    variant="primary"
                    className='w-fit'
                    onClick={() => setIsModalOpen(true)}
                >
                    افزودن قیمت‌گذاری جدید
                </Button>
            </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={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {pricingItems.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={4} className="text-center py-8 text-gray-500">
                                    هیچ آیتم قیمت‌گذاری یافت نشد
                                </td>
                            </tr>
                        ) : (
                            pricingItems.map((item: PricingItem) => (
                                <tr key={item._id} className='tr'>
                                    <Td text={item.type} />
                                    <Td text={`${item.price.toLocaleString('fa-IR')} تومان`} />
                                    <Td text={new Date(item.createdAt).toLocaleDateString('fa-IR')} />
                                    <Td text={new Date(item.updatedAt).toLocaleDateString('fa-IR')} />
                                    <Td text={''}>
                                        <div className='flex items-center gap-2'>
                                            <Edit
                                                onClick={() => handleEditPricing(item)}
                                                color='#8C90A3'
                                                size={16}
                                                className="cursor-pointer hover:text-blue-500"
                                            />
                                            <TrashWithConfrim
                                                onDelete={() => handleDeletePricing(item._id)}
                                                isLoading={deletePricingMutation.isPending}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <AddPricingModal
                isOpen={isModalOpen}
                onClose={() => setIsModalOpen(false)}
            />

            <EditPricingModal
                isOpen={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                pricingItem={selectedPricingItem}
            />
        </div>
    )
}

export default Pricing