import { CloseCircle, Paperclip2 } from 'iconsax-react'
import { FC, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDropzone } from 'react-dropzone'
import { useSingleUpload } from '@/pages/setting/personality/hooks/usePersonalityData'


type Props = {
    title?: string
    useUploadService?: boolean,
    onUploadComplete?: (urls: string[]) => void,
    onUploadError?: (error: Error) => void,
    onChange?: (files: File[]) => void
}

const UploadButton: FC<Props> = (props) => {

    const { t } = useTranslation()
    const { title } = props

    const [files, setFiles] = useState<File[]>([])
    const [isUploading, setIsUploading] = useState<boolean>(false)

    const { mutateAsync: singleUpload } = useSingleUpload()

    const onDrop = useCallback(async (acceptedFiles: File[]) => {
        if (props.useUploadService) {
            setIsUploading(true)
            try {
                const uploadPromises = acceptedFiles.map(file => singleUpload(file))
                const results = await Promise.all(uploadPromises)
                const urls = results.map(result => result?.data?.url).filter(Boolean)

                if (props.onUploadComplete) {
                    props.onUploadComplete(urls)
                }

                const newFiles = [...files, ...acceptedFiles]
                setFiles(newFiles)

                if (props.onChange) {
                    props.onChange(newFiles)
                }
            } catch (error) {
                console.error('Upload failed:', error)
                if (props.onUploadError) {
                    props.onUploadError(error as Error)
                }
                // Fallback to normal file handling
                const newFiles = [...files, ...acceptedFiles]
                setFiles(newFiles)

                if (props.onChange) {
                    props.onChange(newFiles)
                }
            } finally {
                setIsUploading(false)
            }
        } else {
            // Original behavior
            const newFiles = [...files, ...acceptedFiles]
            setFiles(newFiles)

            if (props.onChange) {
                props.onChange(newFiles)
            }
        }
    }, [files, props.useUploadService, props.onUploadComplete, props.onUploadError, props.onChange, singleUpload])

    const { getRootProps, getInputProps } = useDropzone({ onDrop })

    const handleRemove = (index: number) => {
        const array = [...files]
        array.splice(index, 1)
        setFiles(array)

        if (props.onChange) {
            props.onChange(array)
        }
    }


    return (
        <div className='flex flex-col gap-4 sm:flex-row'>
            <div {...getRootProps()} className='h-10 bg-[#ECEEF5] rounded-full flex gap-2 items-center px-3 cursor-pointer'>
                <input {...getInputProps()} />

                <Paperclip2 size={20} color='#000' />
                <div className='text-xs'>{isUploading ? 'در حال آپلود...' : (title ? title : t('attachment_select'))}</div>
            </div>

            {files.map((file, index) => (
                <div key={file.name} className='bg-[#EBEDF5] text-xs flex gap-2 h-10 rounded-full items-center px-3'>
                    <span>{file.name}</span>
                    <CloseCircle size={19} color='#D52903' className='cursor-pointer' onClick={() => handleRemove(index)} />
                </div>
            ))}
        </div>
    )
}

export default UploadButton