import { FC, useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDropzone } from 'react-dropzone'
import { CloseCircle } from 'iconsax-react'


type Props = {
    label: string,
    isMultiple?: boolean,
    onChange?: (file: File[]) => void;
    isReset?: boolean;
    accept?: string;
}

const MIME_TO_EXTENSIONS: Record<string, string[]> = {
    'image/png': ['.png'],
    'image/svg+xml': ['.svg'],
    'image/jpeg': ['.jpg', '.jpeg'],
    'image/gif': ['.gif'],
    'image/webp': ['.webp'],
}

const buildAcceptTypes = (accept?: string) => {
    if (!accept) return undefined

    return accept.split(',').reduce<Record<string, string[]>>((acc, type) => {
        const trimmed = type.trim()
        if (trimmed.startsWith('.')) {
            const ext = trimmed.toLowerCase()
            const mimeEntry = Object.entries(MIME_TO_EXTENSIONS).find(([, exts]) => exts.includes(ext))
            if (mimeEntry) {
                acc[mimeEntry[0]] = mimeEntry[1]
            }
        } else if (MIME_TO_EXTENSIONS[trimmed]) {
            acc[trimmed] = MIME_TO_EXTENSIONS[trimmed]
        } else {
            acc[trimmed] = []
        }
        return acc
    }, {})
}

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

    const { t } = useTranslation('global')
    const [files, setFiles] = useState<File[]>([])

    const onDrop = useCallback((acceptedFiles: File[]) => {
        if (props.isMultiple) {
            const array = [...files, ...acceptedFiles]
            setFiles(array)
            if (props.onChange) {
                props.onChange(array);
            }
        } else {
            setFiles([acceptedFiles[0]])
            if (props.onChange) {
                props.onChange([acceptedFiles[0]])
            }
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [files])
    const acceptTypes = buildAcceptTypes(props.accept)
    const { getRootProps, getInputProps } = useDropzone({
        onDrop,
        accept: acceptTypes,
        multiple: props.isMultiple,
    })

    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'>
                    <input {...getInputProps()} />

                    {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