import { __rest } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useCallback, useEffect, useMemo } from 'react';
import { Box, IconButton, Typography, useMediaQuery, useTheme } from '@mui/material';
import { styled } from '@mui/material/styles';
import Icon from '@mui/material/Icon';
import classNames from 'classnames';
import { ReactSortable } from 'react-sortablejs';
import { PREFIX } from './constants';
import filter from './filter';
import { MEDIA_TYPE_DOCUMENT } from '../../../constants/Media';
const classes = {
    previewRoot: `${PREFIX}-preview-root`,
    media: `${PREFIX}-media`,
    delete: `${PREFIX}-delete`,
    title: `${PREFIX}-title`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'PreviewRoot'
})(() => ({}));
const SORTABLE_ID = 'file_sort';
const PreviewComponent = React.forwardRef((props, ref) => {
    // PROPS
    const { className, onChange, value = [] } = props, rest = __rest(props, ["className", "onChange", "value"]);
    // HOOKS
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    // MEMO
    const medias = useMemo(() => value.filter(filter), [value]);
    // EFFECTS
    useEffect(() => {
        if (typeof document === undefined) {
            return null;
        }
        const sortable = document.getElementById(SORTABLE_ID);
        if (sortable) {
            sortable.scrollLeft = sortable.scrollWidth;
        }
    }, [medias]);
    // HANDLERS
    const handleSort = useCallback((medias) => {
        onChange && onChange([...value.filter((media) => medias.findIndex((m) => m.id === media.id) === -1), ...medias]);
    }, [onChange, value]);
    const handleDelete = useCallback((id) => () => onChange && onChange(value.filter((media) => media.id !== id)), [onChange, value]);
    // RENDER
    const mediaElements = useMemo(() => medias.map((media) => (_jsxs(Box, Object.assign({ className: classes.media, sx: { backgroundImage: `url(${(media === null || media === void 0 ? void 0 : media.image_thumbnail) ? media.image_thumbnail.url : media.image})` } }, { children: [_jsx(IconButton, Object.assign({ className: classes.delete, onClick: handleDelete(media.id), size: "small" }, { children: _jsx(Icon, { children: "delete" }) })), media.title && _jsxs(Typography, Object.assign({ className: classes.title }, { children: [media.type === MEDIA_TYPE_DOCUMENT && _jsx(Icon, { children: "picture_as_pdf" }), media.title] }))] }), media.id))), [medias]);
    return _jsx(Root, Object.assign({ ref: ref, className: classNames(className, classes.previewRoot) }, rest, { children: medias.length > 0 && (isMobile ?
            _jsx(Box, Object.assign({ id: SORTABLE_ID }, { children: mediaElements })) :
            _jsx(ReactSortable, Object.assign({ id: SORTABLE_ID, list: medias, setList: handleSort }, { children: mediaElements }))) }));
});
export default PreviewComponent;
