import { FC, useEffect, useState } from 'react'
import { TemplateResponseType } from '../types/Types'
import Radio from '@/components/Radio'
import { Brush2, Trash } from 'iconsax-react'
import { useSetSelectedTemplate, useDeleteTemplate } from '../hooks/usePersonalityData'
import { Link } from 'react-router-dom'
import { Paths } from '@/utils/Paths'
import ModalConfrim from '@/components/ModalConfrim'

const Templete: FC<{
    item: TemplateResponseType
    selectedTemplateId?: string
    onOptimisticSelect?: (id: string | null) => void
}> = ({ item, selectedTemplateId, onOptimisticSelect }) => {

    const [isActive, setIsActive] = useState(item.selected)
    const [isShowDeleteModal, setIsShowDeleteModal] = useState(false)

    const { mutate: setSelectedTemplate } = useSetSelectedTemplate()
    const { mutate: deleteTemplate, isPending: isDeleting } = useDeleteTemplate()

    const handleChangeSelectedTemplate = (id: string) => {
        // Optimistic update - بلافاصله UI را به‌روزرسانی کن
        setIsActive(true)
        onOptimisticSelect?.(id)

        setSelectedTemplate(id, {
            onError: () => {
                // اگر خطا رخ داد، state را به حالت قبلی برگردان
                setIsActive(item.selected)
                onOptimisticSelect?.(null)
            }
        })
    }

    const handleDeleteTemplate = () => {
        deleteTemplate(item.id, {
            onSuccess: () => {
                setIsShowDeleteModal(false)
            }
        })
    }

    useEffect(() => {
        if (selectedTemplateId) {
            setIsActive(selectedTemplateId === item.id)
        } else {
            setIsActive(item.selected)
        }
    }, [item.selected, selectedTemplateId, item.id])

    return (
        <>
            <div key={item.id} className='flex-1 lg:max-w-[25%] min-w-[20%] w-full bg-white rounded-3xl p-4'>
                <div className='h-[140px] bg-gray-200 rounded-3xl'>
                    <img src={item.thumbnailUrl} alt={item.name} className='w-full h-full object-contain' />
                </div>
                <div className='mt-4 flex justify-between items-center'>
                    <div className='flex gap-2 items-center'>
                        <Radio isActive={isActive} onChange={handleChangeSelectedTemplate} value={item.id} />
                        <div className='text-sm'>{item.name}</div>
                    </div>
                    <div className='flex gap-2 items-center'>
                        <Link to={`${Paths.settingPersonality}/${item.id}`}>
                            <Brush2 size={20} color='black' />
                        </Link>
                        <button onClick={() => setIsShowDeleteModal(true)} className='p-1'>
                            <Trash size={20} color='red' />
                        </button>
                    </div>
                </div>
            </div>

            <ModalConfrim
                isOpen={isShowDeleteModal}
                close={() => setIsShowDeleteModal(false)}
                onConfrim={handleDeleteTemplate}
                isLoading={isDeleting}
                title="حذف قالب"
                label={`آیا از حذف قالب "${item.name}" اطمینان دارید؟`}
            />
        </>
    )
}

export default Templete