import { useState, type FC } from 'react'
import { useGetIcons, useDeleteIcon } from '../hooks/useIconData'
import { useTranslation } from 'react-i18next'
import Button from '../../../components/Button'
import { Add } from 'iconsax-react'
import CreateIcon from './components/CreateIcon'
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 { IconType } from '../types/Types'
import moment from 'moment-jalaali'

const IconsList: FC = () => {

    const { t } = useTranslation('global')
    const [showModal, setShowModal] = useState<boolean>(false)
    const [search, setSearch] = useState<string>('')
    const { data: iconsData, isLoading, refetch } = useGetIcons()
    const deleteIcon = useDeleteIcon()

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

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

    const icons = (iconsData as unknown as { data?: IconType[] })?.data || []
    const filteredIcons = icons.filter((icon: IconType) =>
        icon.url.toLowerCase().includes(search.toLowerCase()) ||
        icon.group?.name?.toLowerCase().includes(search.toLowerCase())
    )

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

                <Button
                    className='w-[172px]'
                    onClick={() => setShowModal(true)}
                >
                    <div className='flex gap-2 items-center'>
                        <Add size={20} color='white' />
                        <div>
                            {t('icon.add_new_icon')}
                        </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('icon.url')} />
                                    <Td text={t('icon.group')} />
                                    <Td text={t('icon.created_at')} />
                                    <Td text={''} />
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    filteredIcons.map((item: IconType) => {
                                        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={deleteIcon.isPending}
                                                        />
                                                    </div>
                                                </Td>
                                            </tr>
                                        )
                                    })
                                }
                            </tbody>
                        </table>
                    </div>
            }

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

export default IconsList
