import { CloseCircle, DocumentUpload, Gallery } from 'iconsax-react'
import { FC, useCallback, useEffect, useState } from 'react'
import { useDropzone } from 'react-dropzone';
import { useTranslation } from 'react-i18next';
import { clx } from '../helpers/utils';
import { useSingleUpload } from '@/pages/setting/personality/hooks/usePersonalityData';

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

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

    const { t } = useTranslation('global')
    const [files, setFiles] = useState<File[]>([])
    const [perviews, setPerviews] = useState<string[]>(props.preview ? props.preview : [])
    const [isFill, setIsFill] = useState<boolean>(false)
    const [cover, setCover] = useState<string>(props.coverUrl ? props.coverUrl : '')
    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)
                    props.onChange(array)
                } else {
                    setFiles([acceptedFiles[0]])
                    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)
                    props.onChange(array)
                } else {
                    setFiles([acceptedFiles[0]])
                    props.onChange([acceptedFiles[0]])
                }
            } finally {
                setIsUploading(false)
            }
        } else {
            // Original behavior
            if (props.isMultiple) {
                const array = [...files]
                array.push(acceptedFiles[0])
                setFiles(array)
                props.onChange(array)
            } else {
                setFiles([acceptedFiles[0]])
                props.onChange([acceptedFiles[0]])
            }
        }
    }, [files, props.useUploadService, props.onUploadComplete, props.onUploadError, singleUpload])

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

    const handleDelete = (index: number) => {
        const array = [...files]
        array.splice(index, 1)
        setFiles(array)
        props.onChange(array)
    }

    const handleDeletePreview = (index: number) => {
        const array = [...perviews];
        array.splice(index, 1);
        setPerviews(array);
        if (props.onChangePreview) {
            props.onChangePreview(array);
        }
        if (props.onDelete) {
            props.onDelete()
        }
    }

    useEffect(() => {

        if (props.preview && props.preview.length > 0 && !isFill) {
            setPerviews(props.preview)

            setIsFill(true)
        }

    }, [props.preview, isFill])

    useEffect(() => {
        setCover(props.coverUrl ? props.coverUrl : '')
    }, [props.coverUrl])

    useEffect(() => {
        if (props.isReset) {
            setFiles([])
            setPerviews([])
        }
    }, [props.isReset])


    return (
        <div>
            <div {...getRootProps()} className='w-full py-8 border border-dashed border-description flex flex-col justify-center items-center gap-4 rounded-2xl'>
                <input {...getInputProps()} />
                <Gallery
                    className='size-8'
                    color='#8C90A3'
                />
                <div className='text-description text-xs'>
                    {isUploading ? 'در حال آپلود...' : props.label}
                </div>

                <div className='flex items-center gap-2'>
                    <DocumentUpload
                        className='size-4'
                        color='black'
                    />
                    <div className='text-xs'>{t('upload')}</div>
                </div>
            </div>

            {
                (perviews && perviews.length > 0) || files.length > 0 ? (
                    <div className='mt-4 flex gap-4 items-center'>
                        {/* اگر preview از props وجود دارد، فقط previewها را نمایش بده */}
                        {
                            perviews && perviews.length > 0 ? perviews.map((item, index) => {
                                return (
                                    <div key={index} className='flex items-center gap-2'>
                                        <div key={index} className='flex relative items-center gap-2'>
                                            <img onClick={() => {
                                                if (props.getCover) {
                                                    setCover(item)
                                                    props.getCover(item)
                                                }
                                            }} src={item}
                                                className={clx(
                                                    'size-10 rounded-full object-cover',
                                                    cover === item ? 'border-2 border-red-400' : ''
                                                )} />
                                            <div onClick={() => handleDeletePreview(index)} className='absolute -left-2 -top-2 shadow-md bg-white size-5 rounded-full flex justify-center items-center'>
                                                <CloseCircle className='size-4 ' color='red' />
                                            </div>
                                        </div>
                                    </div>
                                )
                            }) : files.map((file, index) => {
                                if (props.isFile) {
                                    return (
                                        <div key={index} className='flex border p-2 rounded-lg items-center gap-2'>
                                            <div className='flex relative items-center gap-2'>
                                                <div className='text-xs'>{file.name}</div>
                                                <div className='absolute -left-4 -top-4 shadow-md bg-white size-5 rounded-full flex justify-center items-center'>
                                                    <CloseCircle onClick={() => handleDelete(index)} className='size-4 ' color='red' />
                                                </div>
                                            </div>
                                        </div>
                                    )
                                }
                                else
                                    return (
                                        <div key={index} className='flex items-center gap-2'>
                                            <div key={index} className='flex relative items-center gap-2'>
                                                <img src={URL.createObjectURL(file)} alt={file.name} className='size-10 rounded-full object-cover' />
                                                <div className='absolute -left-2 -top-2 shadow-md bg-white size-5 rounded-full flex justify-center items-center'>
                                                    <CloseCircle onClick={() => handleDelete(index)} className='size-4 ' color='red' />
                                                </div>
                                            </div>
                                        </div>
                                    )
                            })
                        }
                    </div>
                ) : null
            }

        </div>
    )
}

export default UploadBoxDraggble