import { useState, type FC } from 'react'
import { useGetStickers, useDeleteSticker } from '../hooks/useStickerData'
import { useTranslation } from 'react-i18next'
import Button from '../../../components/Button'
import { Add } from 'iconsax-react'
import CreateSticker from './components/CreateSticker'
import Td from '../../../components/Td'
import Input from '../../../components/Input'
import PageLoading from '../../../components/PageLoading'
import TrashWithConfrim from '../../../components/TrashWithConfrim'
import { toast } from '../../../components/Toast';
import { ErrorType } from '../../../helpers/types'
import { StickerType } from '../types/Types'
import moment from 'moment-jalaali'

const StickersList: FC = () => {

    const { t } = useTranslation('global')
    const [showModal, setShowModal] = useState<boolean>(false)
    const [search, setSearch] = useState<string>('')
    const { data: stickersData, isLoading, refetch } = useGetStickers()
    const deleteSticker = useDeleteSticker()

    const handleCloseModal = () => {
        setShowModal(false)
        refetch()
    }

    const handleDelete = (id: string) => {
        deleteSticker.mutate(id, {
            onSuccess: () => {
                refetch()
                toast(t('success'), 'success')
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error?.message[0], 'error')
            }
        })
    }

    const stickers = (stickersData as unknown as { data?: StickerType[] })?.data || []
    const filteredStickers = stickers.filter((sticker: StickerType) =>
        sticker.url.toLowerCase().includes(search.toLowerCase()) ||
        sticker.group?.name?.toLowerCase().includes(search.toLowerCase())
    )

    return (
        <div className='mt-4 min-h-[500px]'>
            <div className='flex justify-between items-center'>
                <div>
                    {t('sticker.list_sticker')}
                </div>

                <Button
                    className='w-[172px]'
                    onClick={() => setShowModal(true)}
                >
                    <div className='flex gap-2 items-center'>
                        <Add size={20} color='white' />
                        <div>
                            {t('sticker.add_new_sticker')}
                        </div>
                    </div>
                </Button>
            </div>

            <div className='mt-4'>
                <div className='flex justify-end items-center'>
                    <div className='xl:w-[300px] w-full'>
                        <Input
                            variant='search'
                            placeholder={t('ads.search')}
                            className='bg-white w-full'
                            onChangeSearchFinal={(value) => setSearch(value)}
                        />
                    </div>
                </div>
            </div>

            {
                isLoading ?
                    <PageLoading />
                    :
                    <div className='relative overflow-x-auto rounded-3xl mt-9 w-full'>
                        <table className='w-full text-sm'>
                            <thead className='thead'>
                                <tr>
                                    <Td text={t('sticker.url')} />
                                    <Td text={t('sticker.group')} />
                                    <Td text={t('sticker.created_at')} />
                                    <Td text={''} />
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    filteredStickers.map((item: StickerType) => {
                                        return (
                                            <tr key={item.id} className='tr'>
                                                <Td text={''}>
                                                    <div className='flex items-center gap-3'>
                                                        <div className='size-10 rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center'>
                                                            <img
                                                                src={item.url}
                                                                alt={item.url}
                                                                className='size-full object-contain'
                                                                onError={(e) => {
                                                                    const target = e.target as HTMLImageElement
                                                                    target.style.display = 'none'
                                                                }}
                                                            />
                                                        </div>
                                                        <div className='truncate max-w-xs' title={item.url}>
                                                            {item.url}
                                                        </div>
                                                    </div>
                                                </Td>
                                                <Td text={item.group?.name || '-'} />
                                                <Td text={moment(item.createdAt).format('jYYYY-jMM-jDD')} />
                                                <Td text={''}>
                                                    <div className='flex gap-2 items-center'>
                                                        <TrashWithConfrim
                                                            onDelete={() => handleDelete(item.id)}
                                                            isLoading={deleteSticker.isPending}
                                                        />
                                                    </div>
                                                </Td>
                                            </tr>
                                        )
                                    })
                                }
                            </tbody>
                        </table>
                    </div>
            }

            <CreateSticker
                open={showModal}
                close={handleCloseModal}
            />
        </div>
    )
}

export default StickersList
