import { withoutDefaults } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useRafRender } from '../../hooks/useRafRender';
import React 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';
import { DataExtension } from '../DataExtension/DataExtension';

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.dataExtension?.shouldDisplayArchive && (
          <DataExtension.CustomColumnsArchivedItemsCTAButton
            dataExtension={state.dataExtension}
            onCloseSidePanel={() => state.closeSidePanel?.()}
            dataHook="custom-fields"
          />
        )}
        <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);
