import { AddItem, Box, Divider, SidePanel } from '@wix/design-system';
import React, { lazy, Suspense, 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 { FieldsSourceAddFieldCTA } from '../CustomFieldsPanel/FieldsSourceAddFieldCTA';

// ArchivedItems is an optional feature module — load it on demand so it stays
// out of the core bundle.
const ArchivedItemsCTAButton = lazy(() =>
  import('../ArchivedItemsPanel/ArchivedItemsCTAButton').then((m) => ({
    default: m.ArchivedItemsCTAButton,
  })),
);

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, collectionFieldsSource } = state;
  const archive = collectionFieldsSource?.fieldsSource.archive;
  const deleteFieldModal =
    collectionFieldsSource?.customFieldsPanel.deleteFieldModal;
  const schemaCtx = useSchemaContext();
  const isSchema = !!schemaCtx?.schema;
  const isEditable = !!collectionFieldsSource || isSchema;

  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 hasFieldsSource = !!collectionFieldsSource;

  // Show search if there's a fields source OR if there are more than 5 columns
  const shouldShowSearch = hasFieldsSource || 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} />
          ) : (
            <>
              {archive?.shouldDisplay && deleteFieldModal && (
                <Suspense fallback={null}>
                  <ArchivedItemsCTAButton
                    archive={archive}
                    deleteFieldModal={deleteFieldModal}
                    onCloseSidePanel={() => state.onClose()}
                    dataHook="custom-columns"
                  />
                </Suspense>
              )}
              <ColumnsList state={state} />
            </>
          )}
        </ScrollableContent>
        {collectionFieldsSource && (
          <FieldsSourceAddFieldCTA source={collectionFieldsSource} />
        )}
        {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>
    </>
  );
}

export const CustomColumnsPanel = observer(_CustomColumnsPanel);
