import { jsx, jsxs } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { styled } from "@mui/material/styles";
import apollo_core, { FontVariantToken } from "@uipath/apollo-core";
import react from "react";
import { ErrorCode, useDropzone } from "react-dropzone";
import { ApTypography } from "../../../ap-typography/index.js";
import { useAttachments } from "../../providers/attachements-provider.js";
import { useChatState } from "../../providers/chat-state-provider.js";
import { useError } from "../../providers/error-provider.js";
import { parseFiles } from "../../utils/file-reader.js";
const DropzoneRoot = styled('div')({
    height: '100%',
    position: 'relative'
});
const DropzoneContent = styled('div')(({ isDragActive })=>({
        opacity: isDragActive ? 0.3 : 1
    }));
const DropzoneOverlay = styled('div')(()=>({
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        textAlign: 'center',
        pointerEvents: 'none',
        border: `${apollo_core.Border.BorderThickM} dashed var(--color-border)`,
        borderRadius: apollo_core.Border.BorderRadiusL,
        margin: 0,
        padding: apollo_core.Spacing.SpacingXxl,
        gap: apollo_core.Spacing.SpacingM,
        height: '100%',
        width: '100%',
        boxSizing: 'border-box'
    }));
function AutopilotChatDropzoneComponent({ children, ...dropzoneOptions }) {
    const { _ } = useLingui();
    const { addAttachments, attachments } = useAttachments();
    const { setError } = useError();
    const { disabledFeatures, allowedAttachments } = useChatState();
    const attachmentsCountRef = react.useRef(attachments.length);
    attachmentsCountRef.current = attachments.length;
    const handleRejections = react.useCallback((parsedFiles, fileRejections)=>{
        if (!allowedAttachments.multiple && (parsedFiles.length > 1 || attachmentsCountRef.current > 0 || fileRejections.length > 1)) {
            setError(_({
                id: 'autopilot-chat.error.multiple-files'
            }));
            return true;
        }
        if (fileRejections.length > 0) {
            const tooManyFilesRejection = fileRejections.find((rejection)=>rejection.errors[0]?.code === ErrorCode.TooManyFiles);
            if (tooManyFilesRejection) {
                const maxCount = allowedAttachments.maxCount;
                setError(_({
                    id: 'autopilot-chat.error.too-many-files',
                    values: {
                        maxCount: maxCount
                    }
                }));
                return true;
            }
            const errorMessages = [];
            for (const { errors, file } of fileRejections){
                const errorCode = errors[0]?.code;
                if (errorCode === ErrorCode.FileTooLarge) {
                    const fileSizeMB = Math.round(file.size / 1024 / 1024);
                    const fileName = file.name;
                    const maxSize = allowedAttachments.maxSize / 1024 / 1024;
                    errorMessages.push(_({
                        id: 'autopilot-chat.error.file-too-large',
                        values: {
                            fileName: fileName,
                            fileSizeMB: fileSizeMB,
                            maxSize: maxSize
                        }
                    }));
                }
                if (errorCode === ErrorCode.FileInvalidType) {
                    const fileName = file.name;
                    errorMessages.push(_({
                        id: 'autopilot-chat.error.file-invalid-type',
                        values: {
                            fileName: fileName
                        }
                    }));
                }
            }
            if (errorMessages.length > 0) setError(errorMessages.join('\n'));
        }
        return false;
    }, [
        _,
        setError,
        allowedAttachments.maxCount,
        allowedAttachments.maxSize,
        allowedAttachments.multiple
    ]);
    const handleDrop = react.useCallback(async (files, fileRejections)=>{
        try {
            const parsedFiles = await parseFiles(files);
            const shouldReturn = handleRejections(parsedFiles, fileRejections);
            if (shouldReturn) return;
            if (0 === fileRejections.length) setError(void 0);
            if (allowedAttachments.multiple) addAttachments(parsedFiles);
            else if (1 === parsedFiles.length) addAttachments([
                parsedFiles[0]
            ]);
        } catch (error) {
            setError(error);
            return;
        }
    }, [
        addAttachments,
        setError,
        allowedAttachments.multiple,
        handleRejections
    ]);
    const { getRootProps, getInputProps, isDragActive } = useDropzone({
        noClick: true,
        noKeyboard: true,
        onDrop: handleDrop,
        accept: allowedAttachments.types,
        maxSize: allowedAttachments.maxSize,
        maxFiles: allowedAttachments.maxCount,
        disabled: disabledFeatures.attachments,
        ...dropzoneOptions
    });
    return /*#__PURE__*/ jsxs(DropzoneRoot, {
        ...getRootProps(),
        children: [
            /*#__PURE__*/ jsx("input", {
                ...getInputProps(),
                multiple: allowedAttachments.multiple,
                style: {
                    display: 'none'
                }
            }),
            /*#__PURE__*/ jsx(DropzoneContent, {
                isDragActive: isDragActive,
                children: children
            }),
            isDragActive && /*#__PURE__*/ jsxs(DropzoneOverlay, {
                children: [
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: FontVariantToken.fontSizeMBold,
                        color: 'var(--color-foreground)',
                        children: _({
                            id: 'autopilot-chat.dropzone.overlay-title'
                        })
                    }),
                    allowedAttachments.maxCount && allowedAttachments.maxCount > 1 && allowedAttachments.multiple && (()=>{
                        const maxCount = allowedAttachments.maxCount;
                        return /*#__PURE__*/ jsx(ApTypography, {
                            variant: FontVariantToken.fontSizeS,
                            color: 'var(--color-foreground)',
                            children: _({
                                id: 'autopilot-chat.dropzone.overlay-max-count',
                                values: {
                                    maxCount: maxCount
                                }
                            })
                        });
                    })(),
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: FontVariantToken.fontSizeS,
                        color: 'var(--color-foreground)',
                        children: (()=>{
                            const maxSize = allowedAttachments.maxSize / 1024 / 1024;
                            return _({
                                id: 'autopilot-chat.dropzone.overlay-max-size',
                                values: {
                                    maxSize: maxSize
                                }
                            });
                        })()
                    }),
                    /*#__PURE__*/ jsx(ApTypography, {
                        variant: FontVariantToken.fontSizeS,
                        color: 'var(--color-foreground)',
                        children: (()=>{
                            const fileTypes = Object.values(allowedAttachments.types).flat().join(', ');
                            return _({
                                id: 'autopilot-chat.dropzone.allowed-file-types',
                                values: {
                                    fileTypes: fileTypes
                                }
                            });
                        })()
                    })
                ]
            })
        ]
    });
}
const AutopilotChatDropzone = /*#__PURE__*/ react.memo(AutopilotChatDropzoneComponent);
export { AutopilotChatDropzone };
