import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { forwardRef, useContext, useEffect, useImperativeHandle, useRef, useState, } from 'react';
import Dropzone from 'react-dropzone';
import { useTranslation } from 'react-i18next';
import { Button } from '../../basic';
import CommonContext from '../../configs/CommonContext';
import { toastLoadingAction } from '../../configs/sessionTypes';
import { useMessageUtils } from '../../configs/useMessageUtils';
import UploadService from './UploadService';
import './style.scss';
function AppDropzoneBodyInner({ folder, onSuccess, onError, accept, messages, onDrop, keepName, showConfirmButton = true, disablePreview = false, disableConfirm = false, }, ref) {
    const { t } = useTranslation('upload');
    const { state, dispatch } = useContext(CommonContext);
    const { dispatchError } = useMessageUtils();
    const [file, setFile] = useState();
    const [preview, setPreview] = useState();
    const fileRef = useRef();
    fileRef.current = file;
    const isImageFile = (f) => {
        return f.type?.startsWith('image/') ?? false;
    };
    useEffect(() => {
        if (!file) {
            setPreview(undefined);
            return;
        }
        if (!disablePreview && isImageFile(file)) {
            const url = URL.createObjectURL(file);
            setPreview(url);
            return () => URL.revokeObjectURL(url);
        }
        setPreview(undefined);
    }, [file, disablePreview]);
    const upload = async () => {
        const currentFile = fileRef.current;
        if (!currentFile || state.toastLoading)
            return;
        dispatch(toastLoadingAction(true));
        const data = new FormData();
        data.append('file', currentFile);
        data.append('folder', folder);
        keepName && data.append('keepOriginalName', 'true');
        UploadService.execute(data)
            .then((r) => {
            onSuccess(r.data);
        })
            .catch((err) => {
            dispatchError({ err: 'error.uploading.image', t, key: 'upload' });
            onError?.(err);
        })
            .finally(() => {
            dispatch(toastLoadingAction(false));
        });
    };
    useImperativeHandle(ref, () => ({
        upload,
    }));
    const handleDrop = (files) => {
        if (files.length === 0)
            return;
        setFile(files[0]);
        onDrop?.();
    };
    const handleCancel = () => {
        setFile(undefined);
    };
    const resolveMessage = (key) => {
        const customMessage = messages?.[key]?.trim();
        return (customMessage ||
            t(key, {
                defaultValue: key === 'label.dropzone'
                    ? 'Drag and drop or click to upload a file'
                    : 'You are uploading the following file:',
            }));
    };
    return (_jsxs("div", { className: "dropzone-container", children: [!file && (_jsx(Dropzone, { onDrop: (acceptedFiles) => handleDrop(acceptedFiles), accept: accept, maxFiles: 1, children: ({ getRootProps, getInputProps }) => (_jsxs("div", { ...getRootProps(), className: "dropzone", children: [_jsx("input", { ...getInputProps() }), _jsx("span", { children: resolveMessage('label.dropzone') })] })) })), file && (_jsxs("div", { className: "uploaded-file", children: [preview && _jsx("img", { className: "preview", src: preview, alt: "" }), !preview && (_jsxs(_Fragment, { children: [_jsx("b", { children: resolveMessage('label.uploaded.file') }), _jsx("span", { children: file.name })] })), showConfirmButton && (_jsxs("div", { className: "buttons", children: [_jsx(Button, { onClick: handleCancel, text: t('common:button.cancel', { defaultValue: 'Cancel' }), size: "small", mode: "outlined", color: "danger" }), _jsx(Button, { onClick: upload, text: t('common:button.confirm', { defaultValue: 'Confirm' }), size: "small", mode: "outlined", disabled: disableConfirm })] }))] }))] }));
}
const AppDropzoneBody = forwardRef(AppDropzoneBodyInner);
export default AppDropzoneBody;
