import { jsxs, jsx } from 'react/jsx-runtime';
import { useRef, useState } from 'react';
import Typography from '../Typography/Typography.js';
import Button from '../Button/Button.js';
import IconButton from '../IconButton/IconButton.js';
import Toaster from '../Toast/Toast.js';
import Icon from '../Icon/Icon.js';
import Tooltip from '../Tooltip/Tooltip.js';
import TruncatedTooltip from '../TruncatedTooltip/TruncatedTooltip.js';

const AttachmentButton = ({ label, selectedFiles, onFilesChange, disabled = false, buttonDisplayType = 'attachment', iconName = 'plus_icon', maxFileSizeMB, maxFiles, buttonLabel = 'Select Files', showSelectedFiles = true, buttonVariant = 'primary', deleteButton = true, multiple = true, addAttachmentButton = true, isInfoIconRequired = true, onFileListClick, types = [], attachmentInfoTooltip = '', selectedFileMessage = 'This file is already selected', required = false, errorMessage, truncateMaxLimit = Infinity, onClickAttachmentButton = () => { }, }) => {
    const fileInputRef = useRef(null);
    const [fileError, setFileError] = useState('');
    const fileTypes = {
        image: ['image/jpeg', 'image/png', 'image/svg+xml'],
        video: ['video/mp4', 'video/mpeg', 'video/quicktime'],
        audio: ['audio/mpeg', 'audio/wav', 'audio/ogg'],
        document: [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ],
        archive: [
            'application/zip',
            'application/x-rar-compressed',
            'application/x-7z-compressed',
        ],
        spreadsheet: [
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ],
        excel: [
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ],
        dat: ['.dat', 'application/octet-stream'],
        trg: ['.trg', 'application/octet-stream'],
    };
    const acceptTypes = types.flatMap((type) => fileTypes[type] || []).join(',');
    const getTooltipTitle = () => {
        if (types.length === 0) {
            return 'Any files are allowed.';
        }
        const acceptedFileTypes = types
            .flatMap((type) => fileTypes[type] || [])
            .map((type) => type.split('/')[1]);
        const lastType = acceptedFileTypes.pop();
        return (jsxs("span", { children: [acceptedFileTypes.join(', '), " and ", lastType, " files are allowed.", jsx("br", {}), "Max size: ", maxFileSizeMB, " MB"] }));
    };
    const handleAttachmentClick = () => {
        onClickAttachmentButton();
        setFileError('');
        fileInputRef.current?.click();
    };
    const handleFileChange = () => {
        setFileError('');
        if (fileInputRef.current?.files) {
            const files = Array.from(fileInputRef.current.files);
            if (files.length > 5) {
                setFileError('Maximum file(s) can be uploaded: 5');
                fileInputRef.current.value = '';
                return;
            }
            const newFiles = files.filter((file) => !selectedFiles.some((selectedFile) => selectedFile.name === file.name));
            if (newFiles.length === 0) {
                setFileError(selectedFileMessage);
                fileInputRef.current.value = '';
                return;
            }
            if (typeof maxFiles === 'number' &&
                selectedFiles.length + newFiles.length > maxFiles) {
                setFileError(`You can only select up to ${maxFiles} files.`);
                fileInputRef.current.value = '';
                return;
            }
            if (typeof maxFileSizeMB === 'number') {
                const maxFileSizeBytes = maxFileSizeMB * 1024 * 1024;
                const oversizedFiles = newFiles.filter((file) => file.size > maxFileSizeBytes);
                if (oversizedFiles.length > 0) {
                    setFileError(`Maximum file(s) size allowed: ${maxFileSizeMB} MB.`);
                    fileInputRef.current.value = '';
                    return;
                }
            }
            onFilesChange([...selectedFiles, ...newFiles], newFiles, 'ADD');
            fileInputRef.current.value = '';
        }
    };
    const handleDeleteFile = (index) => {
        const updatedFiles = [...selectedFiles];
        const deletedFile = updatedFiles.splice(index, 1);
        onFilesChange(updatedFiles, deletedFile, 'DELETE');
    };
    return (jsxs("div", { children: [isInfoIconRequired && (jsxs("div", { className: "ff-label-icon", children: [jsx(Typography, { fontWeight: "semi-bold", lineHeight: "18px", as: "span", required: required, children: label }), jsx(Tooltip, { title: attachmentInfoTooltip ? attachmentInfoTooltip : getTooltipTitle(), placement: "bottom-start", children: jsx(Icon, { name: "info", hoverEffect: true }) })] })), (!showSelectedFiles || selectedFiles.length === 0) &&
                (buttonDisplayType === 'attachment' ? (jsx(Button, { variant: buttonVariant, label: buttonLabel, size: "medium", onClick: handleAttachmentClick, disabled: disabled })) : buttonDisplayType === 'icon' ? (jsx(IconButton, { label: buttonLabel, iconName: iconName, onClick: handleAttachmentClick, isDisable: disabled })) : null), jsx("input", { type: "file", ref: fileInputRef, className: "ff-input-field", onChange: handleFileChange, multiple: multiple, accept: acceptTypes, required: required }), fileError && (jsx(Toaster, { isOpen: !!fileError, variant: "info", toastTitle: "Info", toastMessage: fileError, zIndex: 10000000 })), showSelectedFiles &&
                selectedFiles.map((file, index) => (jsxs("div", { className: "ff-attachment-files", onClick: onFileListClick, children: [jsx(Typography, { color: "var(--brand-color)", children: jsx(TruncatedTooltip, { title: file.name, width: truncateMaxLimit }) }), deleteButton && (jsx(Tooltip, { title: "Delete", children: jsx(Icon, { name: "delete", hoverEffect: true, color: "var(--ff-delete-button-attachment)", variant: "danger", onClick: () => handleDeleteFile(index) }) })), index === selectedFiles.length - 1 && addAttachmentButton && (jsx(Tooltip, { title: `${typeof maxFiles === 'number' &&
                                selectedFiles.length >= maxFiles
                                ? `Maximum files can be uploaded: ${maxFiles}`
                                : 'Add File'}`, children: jsx(Icon, { name: "add_file", hoverEffect: true, onClick: handleAttachmentClick, disabled: typeof maxFiles === 'number'
                                    ? !(selectedFiles.length < maxFiles)
                                    : false }) }))] }, file.name))), required && (jsx(Typography, { children: errorMessage, fontSize: 10, className: "error-text" }))] }));
};

export { AttachmentButton as default };
//# sourceMappingURL=AttachmentButton.js.map
