import { useState, type FC } from 'react'
import PageTitle from '@/components/PageTitle'
import { useDeleteSlider, useGetSliders, useUpdateSlider } from './hooks/useSettingData'
import { type SliderItem, type UpdateSliderType } from './types/Types'
import PageLoading from '@/components/PageLoading'
import Error from '@/components/Error'
import Td from '@/components/Td'
import { Calendar, Add, Edit, Eye } from 'iconsax-react'
import Button from '@/components/Button'
import TrashWithConfrim from '@/components/TrashWithConfrim'
import Switch from '@/components/Switch'
import CreateSliderModal from './components/CreateSliderModal'
import EditSliderModal from './components/EditSliderModal'

const Sliders: FC = () => {
    const { data, isLoading, error, refetch } = useGetSliders()
    const updateSlider = useUpdateSlider()
    const deleteSlider = useDeleteSlider()

    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
    const [editingSlider, setEditingSlider] = useState<SliderItem | 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 sliders = data?.results?.sliders || []

    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 getDisplayLocationLabel = (location: 'desktop' | 'mobile') => {
        return location === 'desktop' ? 'دسکتاپ' : 'موبایل'
    }

    const handleStatusToggle = (slider: SliderItem) => {
        const updateData: UpdateSliderType = {
            displayLocation: slider.displayLocation,
            imageUrl: slider.imageUrl,
            altText: slider.altText,
            title: slider.title,
            linkUrl: slider.linkUrl,
            isActive: !slider.isActive,
        }

        updateSlider.mutate({ id: slider._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={'عملیات'} />
                        </tr>
                    </thead>
                    <tbody>
                        {sliders.length === 0 ? (
                            <tr className='tr'>
                                <td colSpan={8} className="text-center py-8 text-gray-500">
                                    هیچ اسلایدری یافت نشد
                                </td>
                            </tr>
                        ) : (
                            sliders.map((slider: SliderItem) => (
                                <tr key={slider._id} className='tr'>
                                    <Td text="">
                                        <div className="flex items-center">
                                            <img
                                                src={slider.imageUrl}
                                                alt={slider.altText}
                                                className="max-w-20 max-h-20 object-contain rounded"
                                            />
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <span className="font-medium">{slider.title}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <span className="text-gray-600 text-sm">
                                                {truncateText(slider.altText)}
                                            </span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="max-w-xs">
                                            <a
                                                href={slider.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(slider.linkUrl)}
                                            </a>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <span className="px-2 py-1 bg-gray-100 rounded text-xs">
                                            {getDisplayLocationLabel(slider.displayLocation)}
                                        </span>
                                    </Td>
                                    <Td text="">
                                        <Switch
                                            active={slider.isActive}
                                            onChange={() => handleStatusToggle(slider)}
                                            isLoading={updateSlider.isPending}
                                        />
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <Calendar size={16} color="#8C90A3" />
                                            <span>{formatDate(slider.createdAt)}</span>
                                        </div>
                                    </Td>
                                    <Td text="">
                                        <div className="flex items-center gap-2">
                                            <button
                                                onClick={() => setEditingSlider(slider)}
                                                className="p-1 hover:bg-gray-100 rounded"
                                            >
                                                <Edit size={16} color="#8C90A3" />
                                            </button>
                                            <TrashWithConfrim
                                                onDelete={() => {
                                                    deleteSlider.mutate(slider._id, {
                                                        onSuccess: () => {
                                                            refetch()
                                                        }
                                                    })
                                                }}
                                                isLoading={deleteSlider.isPending}
                                            />
                                        </div>
                                    </Td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>

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

            {editingSlider && (
                <EditSliderModal
                    slider={editingSlider}
                    isOpen={!!editingSlider}
                    onClose={() => setEditingSlider(null)}
                    onSuccess={() => {
                        setEditingSlider(null)
                        refetch()
                    }}
                />
            )}
        </div>
    )
}

export default Sliders

