import { withoutDefaults } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useRafRender } from '../../hooks/useRafRender';
import React, { lazy, Suspense } from 'react';
import { Box, Divider, SidePanel } from '@wix/design-system';
import { ScrollableContent } from '../ScrollableContent';
import { observer } from 'mobx-react-lite';
import { CustomFieldsList } from './CustomFieldsList';
import { AddCustomFieldCTAButton } from './AddCustomFieldCTAButton';
import { cairoFiltersPanelUsed } from '@wix/bex-core/bi';
import { CustomFieldsPanelState } from '../../state/CustomFields/CustomFieldsPanelState';
import { PatternsSidePanel } from '../SidePanel/PatternsSidePanel';

// Lazy: the archive CTA loads only for sources that archive, so sources that
// don't (e.g. a schema) never pull it into their bundle.
const ArchivedItemsCTAButton = lazy(() =>
  import('../ArchivedItemsPanel/ArchivedItemsCTAButton').then((m) => ({
    default: m.ArchivedItemsCTAButton,
  })),
);

export interface CustomFieldsPanelProps {
  state: CustomFieldsPanelState;
}
export function _CustomFieldsPanel({ state }: CustomFieldsPanelProps) {
  const container = useWixPatternsContainer();
  const { translate: t } = container;
  const origin = 'Custom fields panel';

  const entered = useRafRender();
  if (!entered) {
    return null;
  }

  return (
    <PatternsSidePanel
      dataHook="custom-fields-panel"
      width="100%"
      onClose={() => {
        state.reportBi(
          withoutDefaults(cairoFiltersPanelUsed)({
            isOpened: false,
            feature: 'Manage custom fields',
            origin: 'X Button',
          }),
        );
        state.closeSidePanel?.();
      }}
    >
      <SidePanel.Header
        title={t('cairo.customFields.manageFields.title')}
        subtitle={t('cairo.customFields.manageFields.subtitle')}
      />
      <ScrollableContent
        overflowY
        dataHook="custom-fields-panel-scroll-container"
      >
        {state.archive?.shouldDisplay && (
          <Suspense fallback={null}>
            <ArchivedItemsCTAButton
              archive={state.archive}
              deleteFieldModal={state.deleteFieldModal}
              onCloseSidePanel={() => state.closeSidePanel?.()}
              dataHook="custom-fields"
            />
          </Suspense>
        )}
        <CustomFieldsList state={state} />
      </ScrollableContent>

      <Box direction="vertical" width="100%">
        <Divider direction="horizontal" />
        <Box padding="SP4" direction="vertical">
          <AddCustomFieldCTAButton
            state={state}
            onClick={() => {
              state.openCustomFieldModal({ origin });
            }}
          />
        </Box>
      </Box>
    </PatternsSidePanel>
  );
}

export const CustomFieldsPanel = observer(_CustomFieldsPanel);
