import { AddItem, Box, Divider, SidePanel } from '@wix/design-system';
import React, { useEffect } from 'react';
import { CustomColumnsPanelStateBase } from '../../state/CustomColumnsPanelStateBase';
import { FiltersMap } 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 { ScrollableContent } from '../ScrollableContent';
import { PatternsSidePanel } from '../SidePanel/PatternsSidePanel';
import { useSchemaContext } from '../../providers/SchemaContext';
import { useSidePanelFieldActions } from './useSidePanelFieldActions';

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

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

  const { dragAndDrop, collectionDataExtension } = state;
  const schemaCtx = useSchemaContext();
  const isSchema = !!schemaCtx?.schema;
  const isEditable = !!collectionDataExtension || isSchema;
  const { fieldActionsByColumn, fieldActionsModal } = useSidePanelFieldActions(
    isEditable ? state.columnsCollection.result.items : [],
    schemaCtx?.schema?.fieldActions,
    schemaCtx?.schema?.refresh,
  );

  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;

  const titleKey = isEditable
    ? 'cairo.table.manage-fields.title'
    : 'cairo.table.custom-columns.title';
  const subtitleKey = isEditable
    ? dragAndDrop
      ? 'cairo.table.manage-fields.dragAndDrop.subtitle'
      : 'cairo.table.manage-fields.subtitle'
    : dragAndDrop
    ? 'cairo.table.custom-columns.dragAndDrop.subtitle'
    : 'cairo.table.custom-columns.subtitle';

  return (
    <>
      <PatternsSidePanel
        dataHook="custom-columns-panel"
        width="100%"
        onClose={() => state.onClose()}
      >
        <SidePanel.Header title={t(titleKey)} subtitle={t(subtitleKey)}>
          {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={() => state.onClose()}
                    dataHook="custom-columns"
                  />
                )}
              <ColumnsList state={state} fieldActions={fieldActionsByColumn} />
            </>
          )}
        </ScrollableContent>
        {collectionDataExtension?.DataExtension
          ?.CustomColumnsAddCustomFieldCTAButton && (
          <collectionDataExtension.DataExtension.CustomColumnsAddCustomFieldCTAButton />
        )}
        {schemaCtx?.addField && (
          <Box direction="vertical" width="100%">
            <Divider direction="horizontal" />
            <Box
              padding="SP4"
              width="100%"
              boxSizing="border-box"
              direction="vertical"
            >
              <AddItem
                dataHook="custom-columns-schema-add-field"
                onClick={schemaCtx.addField}
              >
                {t('cairo.customFields.addCustomField.CTA')}
              </AddItem>
            </Box>
          </Box>
        )}
      </PatternsSidePanel>
      {fieldActionsModal}
    </>
  );
}

export const CustomColumnsPanel = observer(_CustomColumnsPanel);
