import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { useEffect, useCallback, useRef, useContext } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from 'antd';
import { v4 as uuidv4 } from 'uuid';
import { arrayMove } from '@dnd-kit/sortable';
import { LabelledSelect } from '../../../components';
import { Field } from '../../../components/field';
import { useConfig, useCommander } from '../../../../../hooks';
import { addValue, setValue } from '../../../../../commands';
import { getUniqueName } from '../../../../../../utils/get-unique-name';
import { CollapsePanel } from '../../../components/collapse-panel';
import { NeedsReloadContext } from '../../../../../providers';
import { SectionHeaderStyled, LayersStyled, ButtonCSS } from './sorting.style';
import { DraggableSortingLayers } from './draggable-sorting-layers';
import { ORDER_PATH, LAYERS_PATH, ORDER_OPTIONS } from './consts';
export const SortingWidget = () => {
    const { t } = useTranslation();
    const { dispatch } = useCommander();
    const { setNeedsReload } = useContext(NeedsReloadContext);
    const layers = useConfig(LAYERS_PATH);
    const prevLayers = useRef(layers);
    useEffect(() => {
        if (layers === prevLayers.current) {
            return;
        }
        setNeedsReload(true);
        prevLayers.current = layers;
    }, [layers]);
    useEffect(() => {
        if (layers) {
            return;
        }
        dispatch(addValue(['globalOptions'], {
            name: 'sortingLayers',
            options: {
                order: ORDER_OPTIONS[0].value,
                layers: [],
            },
        }));
    }, [layers]);
    const handleAddNewLayer = useCallback(() => {
        if (!layers) {
            return;
        }
        dispatch(addValue(LAYERS_PATH, {
            id: uuidv4(),
            name: getUniqueName('layer', layers),
        }));
    }, [dispatch, layers]);
    const handleDragEntity = useCallback((from, to) => {
        if (!layers) {
            return;
        }
        dispatch(setValue(LAYERS_PATH, arrayMove(layers, from, to)));
    }, [layers, dispatch]);
    return (_jsxs(CollapsePanel, { title: t('globalOptions.sorting.title'), deletable: false, children: [_jsx(Field, { path: ORDER_PATH, component: LabelledSelect, label: t('globalOptions.sorting.order.title'), options: ORDER_OPTIONS }), _jsx(SectionHeaderStyled, { children: t('globalOptions.sorting.layers.title') }), _jsx(LayersStyled, { children: layers ? (_jsx(DraggableSortingLayers, { sortingLayers: layers, onDragEntity: handleDragEntity })) : null }), _jsx(Button, { css: ButtonCSS, size: "small", onClick: handleAddNewLayer, children: t('globalOptions.sorting.layers.addNew.title') })] }));
};
