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


type Props = {
    label: string,
    isMultiple?: boolean,
    onChange?: (file: File[]) => void;
    isReset?: boolean;
    useUploadService?: boolean,
    onUploadComplete?: (urls: string[]) => void,
    onUploadError?: (error: Error) => void
}

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

    const { t } = useTranslation('global')
    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)
                }

                if (props.isMultiple) {
                    const array = [...files]
                    array.push(acceptedFiles[0])
                    setFiles(array)
                    if (props.onChange) {
                        props.onChange(array)
                    }
                } else {
                    setFiles([acceptedFiles[0]])
                    if (props.onChange) {
                        props.onChange([acceptedFiles[0]])
                    }
                }
            } catch (error) {
                console.error('Upload failed:', error)
                if (props.onUploadError) {
                    props.onUploadError(error as Error)
                }
                // Fallback to normal file handling
                if (props.isMultiple) {
                    const array = [...files]
                    array.push(acceptedFiles[0])
                    setFiles(array)
                    if (props.onChange) {
                        props.onChange(array)
                    }
                } else {
                    setFiles([acceptedFiles[0]])
                    if (props.onChange) {
                        props.onChange([acceptedFiles[0]])
                    }
                }
            } finally {
                setIsUploading(false)
            }
        } else {
            // Original behavior
            if (props.isMultiple) {
                const array = [...files]
                array.push(acceptedFiles[0])
                setFiles(array)
                if (props.onChange) {
                    props.onChange(array)
                }
            } else {
                setFiles([acceptedFiles[0]])
                if (props.onChange) {
                    props.onChange([acceptedFiles[0]])
                }
            }
        }
    }, [files, props.useUploadService, props.onUploadComplete, props.onUploadError, 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)
        }
    }

    useEffect(() => {

        if (props.isReset) {
            setFiles([])
        }

    }, [props.isReset])



    return (
        <div>
            <div className='text-sm'>{props.label}</div>
            <div className='w-full h-10 mt-1 border border-border rounded-xl items-center px-2 flex gap-2.5'>
                <button {...getRootProps()} className=' w-fit h-7 rounded-lg text-xs px-6 bg-secondary' disabled={isUploading}>
                    <input {...getInputProps()} />

                    {isUploading ? 'در حال آپلود...' : t('select_file')}
                </button>

                <div className='lg:flex gap-2 hidden'>
                    {
                        files?.map((item, index) => (
                            <div key={index} className='flex bg-gray-200 py-1.5 px-2 rounded-lg items-center gap-1'>
                                <CloseCircle onClick={() => handleRemove(index)} size={16} color='red' />
                                <div className='text-xs'>{item.name}</div>
                            </div>
                        ))
                    }
                </div>
            </div>
            <div className='lg:hidden gap-2 flex flex-wrap mt-4'>
                {
                    files?.map((item, index) => (
                        <div key={index} className='flex bg-gray-200 py-1.5 px-2 rounded-lg items-center gap-1'>
                            <CloseCircle onClick={() => handleRemove(index)} size={16} color='red' />
                            <div className='text-xs'>{item.name}</div>
                        </div>
                    ))
                }
            </div>
        </div>
    )
}

export default UploadBox