import { useState, type FC } from 'react'
import PageTitle from '@/components/PageTitle'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'
import Td from '@/components/Td'
import Button from '@/components/Button'
import TrashWithConfrim from '@/components/TrashWithConfrim'
import Switch from '@/components/Switch'
import { useDeleteBanner, useGetBanners, useUpdateBanner } from '@/pages/setting/hooks/useSettingData'
import { type BannerItem, type UpdateBannerType } from '@/pages/setting/types/Types'
import { Calendar, Add, Edit, Eye } from 'iconsax-react'
import CreateBannerModal from './components/CreateBannerModal'
import EditBannerModal from './components/EditBannerModal'

const Banners: FC = () => {
    const { data, isLoading, error, refetch } = useGetBanners()
    const updateBanner = useUpdateBanner()
    const deleteBanner = useDeleteBanner()

    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
    const [editingBanner, setEditingBanner] = useState<BannerItem | 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 banners = data?.results?.banners || []

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

    const truncateText = (text: string, maxLength: number = 30) => {
        if (text.length <= maxLength) return text
        return text.substring(0, maxLength) + '...'
    }

    const handleStatusToggle = (banner: BannerItem) => {
        const updateData: UpdateBannerType = {
            imageUrl: banner.imageUrl,
            altText: banner.altText,
            title: banner.title,
            linkUrl: banner.linkUrl,
            isActive: !banner.isActive,
            order: banner.order,
            displayLocation: banner.displayLocation
        }

        updateBanner.mutate({ id: banner._id, params: updateData })
    }

    return (
        <div>
            <PageTitle />
            <div className="flex justify-between items-center gap-4 mb-5">
                <div className='flex items-center gap-3'>
                    <h1>مدیریت بنرها</h1>
                </div>
                <Button
                    onClick={() => setIsCreateModalOpen(true)}
                    className='w-fit'
                >
                    <div className='flex gap-2 items-center'>
                        <Add size={16} color='#fff' />
                        <span>افزودن بنر جدید</span>
                    </div>
                </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={'محل نمایش'} />
                            <Td text={'ترتیب'} />
                            <Td text={'وضعیت'} />
                            <Td text={'تاریخ ایجاد'} />
                            <Td text={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {banners.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={9} className="text-center py-8 text-gray-500">
                                    هیچ بنری یافت نشد
                                </td>
                            </tr>
                        ) : (
                            banners.map((banner: BannerItem) => (
                                <tr key={banner._id} className='tr'>
                                    <Td text="">
                                        <div className="flex items-center">
                                            <img
                                                src={banner.imageUrl}
                                                alt={banner.altText}
                                                className="max-w-20 max-h-20 object-contain rounded"
                                            />
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <span className="font-medium">{banner.title}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <span className="text-gray-600 text-sm">
                                                {truncateText(banner.altText)}
                                            </span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <a
                                                href={banner.linkUrl}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="text-blue-600 hover:text-blue-800 text-sm flex items-center gap-1"
                                            >
                                                <Eye size={14} />
                                                {truncateText(banner.linkUrl)}
                                            </a>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <span className="capitalize">
                                            {banner.displayLocation === 'desktop' ? 'دسکتاپ' : 'موبایل'}
                                        </span>
                                    </Td>
                                    <Td text={banner.order.toString()} />
                                    <Td text="">
                                        <Switch
                                            active={banner.isActive}
                                            onChange={() => handleStatusToggle(banner)}
                                            isLoading={updateBanner.isPending}
                                        />
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Calendar size={16} color="#8C90A3" />
                                            <span>{formatDate(banner.createdAt)}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <button
                                                onClick={() => setEditingBanner(banner)}
                                                className="p-1 hover:bg-gray-100 rounded"
                                            >
                                                <Edit size={16} color="#8C90A3" />
                                            </button>
                                            <TrashWithConfrim
                                                onDelete={() => {
                                                    deleteBanner.mutate(banner._id, {
                                                        onSuccess: () => {
                                                            refetch()
                                                        }
                                                    })
                                                }}
                                                isLoading={deleteBanner.isPending}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            <CreateBannerModal
                isOpen={isCreateModalOpen}
                onClose={() => setIsCreateModalOpen(false)}
                onSuccess={() => {
                    setIsCreateModalOpen(false)
                    refetch()
                }}
            />

            {editingBanner && (
                <EditBannerModal
                    banner={editingBanner}
                    isOpen={!!editingBanner}
                    onClose={() => setEditingBanner(null)}
                    onSuccess={() => {
                        setEditingBanner(null)
                        refetch()
                    }}
                />
            )}
        </div>
    )
}

export default Banners