import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useCallback, useMemo, useState } from 'react';
import { CircularProgress, IconButton, List, ListItem, ListItemButton, Menu, MenuItem, SwipeableDrawer, useMediaQuery, useTheme, } from '@mui/material';
import Icon from '@mui/material/Icon';
import { PREFIX } from './constants';
import { styled } from '@mui/material/styles';
import classNames from 'classnames';
import { useSCContext } from '@selfcommunity/react-core';
import { FormattedMessage } from 'react-intl';
import MediaChunkUploader from '../../MediaChunkUploader';
import ChunkedUploady from '@rpldy/chunked-uploady';
import { Endpoints } from '@selfcommunity/api-services';
import asUploadButton from './asUploadButton';
import { useSnackbar } from 'notistack';
const classes = {
    triggerRoot: `${PREFIX}-trigger-root`,
    triggerDrawerRoot: `${PREFIX}-trigger-drawer-root`,
    triggerMenuRoot: `${PREFIX}-trigger-menu-root`,
    paper: `${PREFIX}-paper`,
    item: `${PREFIX}-item`,
};
const Root = styled(IconButton, {
    name: PREFIX,
    slot: 'TriggerRoot'
})(() => ({}));
const SwipeableDrawerRoot = styled(SwipeableDrawer, {
    name: PREFIX,
    slot: 'TriggerDrawerRoot'
})(() => ({}));
const MenuRoot = styled(Menu, {
    name: PREFIX,
    slot: 'TriggerMenuRoot'
})(() => ({}));
const PhotoUploadListItemButton = asUploadButton(forwardRef((props, ref) => (_jsx(ListItemButton, Object.assign({}, props, { "aria-label": "upload", ref: ref })))), { accept: 'image/*', capture: 'camera' });
const GalleryUploadListItemButton = asUploadButton(forwardRef((props, ref) => (_jsx(ListItemButton, Object.assign({}, props, { "aria-label": "upload", ref: ref })))), { accept: 'image/*' });
const DocumentUploadListItemButton = asUploadButton(forwardRef((props, ref) => (_jsx(ListItemButton, Object.assign({}, props, { "aria-label": "upload", ref: ref })))), { accept: 'application/pdf' });
const GalleryUploadMenuItem = asUploadButton(forwardRef((props, ref) => (_jsx(MenuItem, Object.assign({}, props, { "aria-label": "upload", ref: ref })))), { accept: 'image/*' });
const DocumentUploadMenuItem = asUploadButton(forwardRef((props, ref) => (_jsx(MenuItem, Object.assign({}, props, { "aria-label": "upload", ref: ref })))), { accept: 'application/pdf' });
export default (_a) => {
    var { className, onAdd = null } = _a, rest = __rest(_a, ["className", "onAdd"]);
    // STATE
    const [anchorEl, setAnchorEl] = useState(null);
    const [isUploading, setIsUploading] = useState(false);
    // CONTEXT
    const scContext = useSCContext();
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const { enqueueSnackbar, closeSnackbar } = useSnackbar();
    // HANDLERS
    const handleOpen = useCallback((event) => {
        setAnchorEl(event.currentTarget);
    }, []);
    const handleClose = useCallback(() => {
        setAnchorEl(null);
    }, []);
    const handleFilterByMime = useCallback((file) => {
        return file.type.startsWith('image/') || file.type === 'application/pdf';
    }, []);
    const handleSuccess = useCallback((media) => {
        onAdd && onAdd(media);
    }, [onAdd]);
    const handleProgress = useCallback((chunks) => {
        //console.log(chunks);
        setIsUploading(Object.keys(chunks).length > 0);
    }, []);
    const handleError = useCallback((chunk, error) => {
        const _snackBar = enqueueSnackbar(`${chunk.name}: ${error}`, {
            variant: 'error',
            anchorOrigin: { horizontal: 'center', vertical: 'top' },
            autoHideDuration: 2000,
            SnackbarProps: {
                onClick: () => {
                    closeSnackbar(_snackBar);
                }
            }
        });
    }, [enqueueSnackbar]);
    const list = useMemo(() => {
        if (isMobile) {
            return [
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(PhotoUploadListItemButton, Object.assign({ inputFieldName: "image" }, { children: _jsx(FormattedMessage, { id: "ui.composer.media.file.photo", defaultMessage: "ui.composer.media.file.photo" }) })) }), "photo"),
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(GalleryUploadListItemButton, Object.assign({ inputFieldName: "image" }, { children: _jsx(FormattedMessage, { id: "ui.composer.media.file.gallery", defaultMessage: "ui.composer.media.file.gallery" }) })) }), "gallery"),
                _jsx(ListItem, Object.assign({ className: classes.item }, { children: _jsx(DocumentUploadListItemButton, Object.assign({ inputFieldName: "document" }, { children: _jsx(FormattedMessage, { id: "ui.composer.media.file.document", defaultMessage: "ui.composer.media.file.document" }) })) }), "document")
            ];
        }
        else {
            return [
                _jsx(GalleryUploadMenuItem, Object.assign({ extraProps: { className: classes.item }, inputFieldName: "image" }, { children: _jsx(FormattedMessage, { id: "ui.composer.media.file.gallery", defaultMessage: "ui.composer.media.file.gallery" }) }), "gallery"),
                _jsx(DocumentUploadMenuItem, Object.assign({ extraProps: { className: classes.item }, inputFieldName: "document" }, { children: _jsx(FormattedMessage, { id: "ui.composer.media.file.document", defaultMessage: "ui.composer.media.file.document" }) }), "document")
            ];
        }
    }, [isMobile, handleFilterByMime, handleSuccess, handleProgress, handleError]);
    return (_jsxs(ChunkedUploady, Object.assign({ destination: {
            url: `${scContext.settings.portal}${Endpoints.ComposerChunkUploadMedia.url()}`,
            method: Endpoints.ComposerChunkUploadMedia.method
        }, fileFilter: handleFilterByMime, chunkSize: 204800, multiple: true }, { children: [_jsx(MediaChunkUploader, { onSuccess: handleSuccess, onProgress: handleProgress, onError: handleError }), _jsx(Root, Object.assign({ className: classNames(className, classes.triggerRoot) }, rest, { "aria-label": "add media", disabled: isUploading, onClick: handleOpen }, { children: isUploading ? _jsx(CircularProgress, { size: 20 }) : _jsx(Icon, { children: "photo_file" }) })), isMobile ? (_jsx(SwipeableDrawerRoot, Object.assign({ onClick: () => setAnchorEl(null), className: classes.triggerDrawerRoot, anchor: "bottom", open: Boolean(anchorEl), onClose: handleClose, onOpen: handleOpen, PaperProps: { className: classes.paper }, disableSwipeToOpen: true }, { children: _jsx(List, { children: list }) }))) : (_jsx(MenuRoot, Object.assign({ onClick: () => setAnchorEl(null), className: classes.triggerMenuRoot, anchorEl: anchorEl, open: Boolean(anchorEl), onClose: handleClose, PaperProps: { className: classes.paper } }, { children: list })))] })));
};
