import { Box, SidePanel } from '@wix/design-system';
import React, { useEffect } from 'react';
import { CustomColumnsState } from '../../state';
import { FiltersMap, withoutDefaults } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { observer } from 'mobx-react-lite';
import { ColumnsList } from './ColumnsList';
import { CustomColumnsSearch } from './CustomColumnsSearch';
import { CustomColumnsNoResults } from './CustomColumnsNoResults';
import { useRafRender } from '../../hooks/useRafRender';
import { cairoFiltersPanelUsed } from '@wix/bex-core/bi';
import { ScrollableContent } from '../ScrollableContent';
import { PatternsSidePanel } from '../SidePanel/PatternsSidePanel';

export interface CustomColumnsPanelProps<T, F extends FiltersMap> {
  state: CustomColumnsState<T, F>;
}

export function _CustomColumnsPanel<T, F extends FiltersMap>({
  state,
}: CustomColumnsPanelProps<T, F>) {
  const entered = useRafRender();
  const { translate: t } = useWixPatternsContainer();

  const { table, dragAndDrop } = state;
  const { sidePanel, collectionDataExtension } = table;

  useEffect(() => state.init(), []);

  if (!entered) {
    return null;
  }

  const hasSearchResults = state.columnsCollection.result.items.length > 0;
  const hasSearchValue = state.searchValue.trim().length > 0;
  const totalColumns = state.orderedColumns.length;
  const isUsingDataExtension = !!collectionDataExtension;

  // Show search if they're using DEx OR if there are more than 5 columns
  const shouldShowSearch = isUsingDataExtension || totalColumns > 5;

  return (
    <PatternsSidePanel
      dataHook="custom-columns-panel"
      width="100%"
      onClose={() => {
        table.reportBi(
          withoutDefaults(cairoFiltersPanelUsed)({
            isOpened: false,
            feature: 'Custom Columns',
            origin: 'X Button',
          }),
        );
        sidePanel.close();
      }}
    >
      <SidePanel.Header
        title={t('cairo.table.custom-columns.title')}
        subtitle={
          dragAndDrop
            ? t('cairo.table.custom-columns.dragAndDrop.subtitle')
            : t('cairo.table.custom-columns.subtitle')
        }
      >
        {shouldShowSearch && (
          <Box padding="0 SP3 SP2 SP3">
            <CustomColumnsSearch state={state} />
          </Box>
        )}
      </SidePanel.Header>
      <ScrollableContent
        overflowY
        dataHook="custom-columns-panel-scroll-container"
        ref={(e) => {
          if (state.dragAndDrop) {
            state.dragAndDrop.listRect.element = e;
          }
        }}
      >
        {hasSearchValue && !hasSearchResults ? (
          <CustomColumnsNoResults state={state} />
        ) : (
          <>
            {collectionDataExtension?.dataExtension?.shouldDisplayArchive &&
              collectionDataExtension?.DataExtension
                ?.CustomColumnsArchivedItemsCTAButton && (
                <collectionDataExtension.DataExtension.CustomColumnsArchivedItemsCTAButton
                  dataExtension={collectionDataExtension.dataExtension}
                  onCloseSidePanel={() => sidePanel.close()}
                  dataHook="custom-columns"
                  actionContainerProps={{ paddingInlineEnd: '12px' }}
                />
              )}
            <ColumnsList state={state} />
          </>
        )}
      </ScrollableContent>
      {collectionDataExtension?.DataExtension
        ?.CustomColumnsAddCustomFieldCTAButton && (
        <collectionDataExtension.DataExtension.CustomColumnsAddCustomFieldCTAButton />
      )}
    </PatternsSidePanel>
  );
}

export const CustomColumnsPanel = observer(_CustomColumnsPanel);
