import React, { useCallback, cloneElement } from 'react';
import { isNil } from 'ramda';
import { ResizablePanes } from '../ResizablePanes';
import { SideButtonsPanel } from '../SideButtonsPanel';
import { usePerspectivesSettings } from '../contexts/PerspectivesSettingsContext';
import { useStyles } from './styles';
var DEFAULT_R_PANE_SIZE = 480;
var MIN_R_PANE_SIZE = 320;
var MAX_R_PANE_SIZE = 640;
export var ProfileResizablePanes = function (_a) {
    var perspectiveId = _a.perspectiveId, children = _a.children, buttonsProps = _a.buttonsProps, disabled = _a.disabled, defaultTab = _a.defaultTab;
    var styles = useStyles();
    var _b = usePerspectivesSettings(perspectiveId), perspectiveSettings = _b.perspectiveSettings, updatePerspectiveSettings = _b.updatePerspectiveSettings;
    var _c = (perspectiveSettings || {}).width, width = _c === void 0 ? DEFAULT_R_PANE_SIZE : _c;
    var active = !isNil(defaultTab) ? defaultTab : perspectiveSettings === null || perspectiveSettings === void 0 ? void 0 : perspectiveSettings.active;
    var activeButton = buttonsProps.find(function (button) { return button.id === active; });
    // When there are no buttons (e.g. the interactions screen drives the panel purely via `active`),
    // open state must not depend on a matching button. Only require `activeButton` when buttons exist,
    // so a stale persisted `active` pointing to a removed tab doesn't open an empty pane.
    var isSidePanelOpen = !isNil(active) && !disabled && (buttonsProps.length === 0 || Boolean(activeButton));
    var handleUpdateSettings = useCallback(function (newSetting) {
        updatePerspectiveSettings(newSetting);
    }, [updatePerspectiveSettings]);
    var toggleActive = useCallback(function (newId) {
        var newActive = active === newId ? null : newId;
        handleUpdateSettings({ active: newActive });
    }, [active, handleUpdateSettings]);
    var resetActive = useCallback(function () {
        handleUpdateSettings({ active: null });
    }, [handleUpdateSettings]);
    var handlePaneSizeChange = useCallback(function (_a) {
        var size = _a.size;
        handleUpdateSettings({ width: size });
    }, [handleUpdateSettings]);
    return (React.createElement(React.Fragment, null,
        React.createElement(ResizablePanes, { className: styles.resizablePanesWrapper, primary: "second", orientation: "vertical", size: isSidePanelOpen ? width : 0, minSize: MIN_R_PANE_SIZE, maxSize: MAX_R_PANE_SIZE, allowResize: isSidePanelOpen, onChange: handlePaneSizeChange, debounceInterval: 2500 },
            React.createElement("div", { className: styles.pane }, children[0]),
            React.createElement("div", { className: styles.pane }, cloneElement(children[1], { active: active, onClose: resetActive }))),
        React.createElement(SideButtonsPanel, { disabled: disabled, buttonsProps: buttonsProps, onButtonClick: toggleActive, activeIndexId: active })));
};
ProfileResizablePanes.displayName = 'ProfileResizablePanes';
