import {__, _n, sprintf} from "@wordpress/i18n";
import {handleError} from "../../../helpers/notifications";
import {getFileFormatedSize} from "../../../../helpers";

export default function FileUpload({added, label, supportedTypes, fileMaxSize, multiple, disabled, addNotification}) {
    /**
     * Handle file
     *
     * @param {Event} e Event
     */
    const handleFileChange = (e) => {
        if (disabled) {
            return;
        }

        if (multiple) {
            if (e.target.files?.length) {
                const files = Array.from(e.target.files);
                
                // Validate file sizes if fileMaxSize is provided
                if (fileMaxSize) {
                    const oversizedFiles = files.filter(file => file.size > fileMaxSize);
                    if (oversizedFiles.length > 0) {
                        // Show notification if addNotification is provided
                        if (addNotification) {
                            handleError({
                                message: "Some files exceed the maximum allowed size.",
                                data: {
                                    files: oversizedFiles,
                                    maxSize: fileMaxSize
                                },
                            }, addNotification, {
                                title: _n("File too large.", "Files too large.", oversizedFiles.length, 'limb-chatbot'),
                                description: sprintf(
                                    _n(
                                        "The file '%s' exceeds the maximum allowed size of %s.",
                                        "The following files exceed the maximum allowed size of %s: %s",
                                        oversizedFiles.length,
                                        'limb-chatbot'
                                    ),
                                    oversizedFiles.length === 1 
                                        ? oversizedFiles[0].name 
                                        : getFileFormatedSize(fileMaxSize),
                                    oversizedFiles.length === 1 
                                        ? getFileFormatedSize(fileMaxSize) 
                                        : oversizedFiles.map(file => `${file.name} (${getFileFormatedSize(file.size)})`).join(', ')
                                ),
                            });
                        }
                        
                        // Filter out oversized files
                        const validFiles = files.filter(file => file.size <= fileMaxSize);
                        if (validFiles.length > 0) {
                            added(validFiles);
                        }
                        // Reset the value
                        e.target.value = '';
                        return;
                    }
                }
                
                added(e.target.files);
                // Reset the value
                e.target.value = '';
            }
        } else {
            const file = e.target.files[0];
            if (file) {
                // Validate file size if fileMaxSize is provided
                if (fileMaxSize && file.size > fileMaxSize) {
                    // Show notification if addNotification is provided
                    if (addNotification) {
                        handleError({
                            message: "File exceeds the maximum allowed size.",
                            data: {
                                file: file,
                                maxSize: fileMaxSize
                            },
                        }, addNotification, {
                            title: __("File too large.", 'limb-chatbot'),
                            description: sprintf(
                                __("The file '%s' exceeds the maximum allowed size of %s.", 'limb-chatbot'),
                                file.name,
                                getFileFormatedSize(fileMaxSize)
                            ),
                        });
                    }
                    // Reset the value
                    e.target.value = '';
                    return;
                }
                
                added(file);
            }
            // Reset the value so the same file can be selected again
            e.target.value = '';
        }
    }

    return (
        <div className={`lbaic-settings-file-upload${disabled ? ' lbaic-settings-disabled' : ''}`}>
            <label className='lbaic-settings-file-upload-in' htmlFor='lbaic-settings-file-upload-test'>
                <input type='file' id='lbaic-settings-file-upload-test' className='lbaic-settings-file-upload-input'
                       accept={supportedTypes?.accept || ''} onChange={handleFileChange} multiple={multiple}/>
                <div className='lbaic-settings-file-upload-inner'>
                    <div className='lbaic-settings-file-upload-icon'>
                        <svg className='lbaic-settings-file-upload-icon-in' xmlns='http://www.w3.org/2000/svg' fill='none'
                             viewBox='0 0 24 24'>
                            <use href='#lbaic-settings-upload'/>
                        </svg>
                    </div>
                    <div className='lbaic-settings-file-upload-desc'>
                        <p className='lbaic-settings-file-upload-desc-main'>{label} <span
                            className='lbaic-settings-file-upload-desc-main-link'>{__("Browse", 'limb-chatbot')}</span></p>
                        <p className='lbaic-settings-file-upload-desc-sub'>{__("Supported file types", 'limb-chatbot')} {supportedTypes?.display || supportedTypes?.accept || ''}</p>
                        {fileMaxSize && (
                            <p className='lbaic-settings-file-upload-desc-sub'>{sprintf(__("Maximum file size: %s", 'limb-chatbot'), getFileFormatedSize(fileMaxSize))}</p>
                        )}
                    </div>
                </div>
            </label>
        </div>
    )
}