import React from 'react';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import {
  AddItem,
  Box,
  Divider,
  Heading,
  InfoIcon,
  SidePanel,
  Tooltip,
} from '@wix/design-system';
import { ToolbarCollectionState } from '../../state';
import { useRafRender } from '../../hooks/useRafRender';
import { MultiLevelSortingList } from './MultiLevelSortingList';
import { ScrollableContent } from '../ScrollableContent';
import { PatternsSidePanel } from '../SidePanel/PatternsSidePanel';

export interface MultiLevelSortingPanelProps<T, F extends FiltersMap> {
  state: ToolbarCollectionState<T, F>;
}

export function _MultiLevelSortingPanel<T, F extends FiltersMap>(
  props: MultiLevelSortingPanelProps<T, F>,
) {
  const { state: table } = props;
  const { multiLevelSorting } = table;

  const { translate: t } = useWixPatternsContainer();
  const entered = useRafRender();

  if (!entered || !multiLevelSorting) {
    return null;
  }

  return (
    <PatternsSidePanel
      dataHook="multi-level-sorting-panel"
      width="100%"
      onClose={() => {
        multiLevelSorting.reportSidePanelClose();
        table.sidePanel.close();
      }}
    >
      <SidePanel.Header
        title={
          <Box gap="SP1" verticalAlign="middle">
            <Heading size="small">
              {t('cairo.table.advanced-sorting.button.tooltip')}
            </Heading>
            <InfoIcon
              size="medium"
              content={t('cairo.table.advanced-sorting.title.tooltip')}
            />
          </Box>
        }
        subtitle={t('cairo.table.advanced-sorting.subtitle')}
      />
      <ScrollableContent
        dataHook="multi-level-sorting-panel-scroll-container"
        overflowY
        smooth
      >
        <MultiLevelSortingList state={multiLevelSorting} />
      </ScrollableContent>
      <Tooltip
        dataHook="multi-level-sorting-add-sort-tooltip"
        disabled={multiLevelSorting.hasAvailableSortingColumns}
        maxWidth={400}
        content={t('cairo.table.advanced-sorting.disabled.cta.tooltip')}
        appendTo="window"
        moveBy={{ y: -24 }}
      >
        <Box direction="vertical" width="100%">
          <Divider direction="horizontal" />

          <Box padding="SP4">
            <AddItem
              dataHook="multi-level-sorting-add-sort"
              disabled={!multiLevelSorting.hasAvailableSortingColumns}
              onClick={() => {
                multiLevelSorting.addSort({ manual: true });
              }}
            >
              {t('cairo.table.advanced-sorting.cta')}
            </AddItem>
          </Box>
        </Box>
      </Tooltip>
    </PatternsSidePanel>
  );
}

export const MultiLevelSortingPanel = observer(_MultiLevelSortingPanel);
