import {
  TableListItem,
  Text,
  IconButton,
  Box,
  BoxProps,
} from '@wix/design-system';
import React, {
  CSSProperties,
  useMemo,
  useCallback,
  lazy,
  Suspense,
} from 'react';
import { Archive, ChevronRight } from '@wix/wix-ui-icons-common';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import type { DeleteFieldModalState, FieldArchive } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';

// Lazy load the ArchivedItemsPanel - only loads when panel is opened
const ArchivedItemsPanel = lazy(() =>
  import('./ArchivedItemsPanel').then((module) => ({
    default: module.ArchivedItemsPanel,
  })),
);

export interface ArchivedItemsCTAButtonProps {
  archive: FieldArchive;
  deleteFieldModal: DeleteFieldModalState;
  onCloseSidePanel: () => void;
  dataHook?: string;
  actionContainerProps?: BoxProps;
}

function _ArchivedItemsCTAButton({
  archive,
  deleteFieldModal,
  onCloseSidePanel,
  dataHook = 'custom-columns',
  actionContainerProps,
}: ArchivedItemsCTAButtonProps) {
  const { translate: t } = useWixPatternsContainer();

  const style = useMemo<CSSProperties>(
    () => ({
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
    }),
    [],
  );

  const handleOpenArchivedPanel = useCallback(() => {
    archive.openPanel();
  }, [archive]);

  const handleCloseArchivedPanel = useCallback(() => {
    archive.closePanel();
  }, [archive]);

  const handleCloseAllPanels = useCallback(() => {
    archive.closePanel();
    onCloseSidePanel();
  }, [archive, onCloseSidePanel]);

  return (
    <>
      <TableListItem
        onClick={handleOpenArchivedPanel}
        dataHook={`${dataHook}-archived-items-button`}
        showDivider
        verticalPadding="tiny"
        horizontalPadding="small"
        options={[
          {
            value: (
              <div style={style}>
                <Archive />
                <Text size="small" weight="normal">
                  {t('cairo.table.custom-columns.section-divider')}
                </Text>
              </div>
            ),
          },
          {
            value: (
              <Box {...actionContainerProps}>
                <IconButton size="tiny" skin="light">
                  <ChevronRight />
                </IconButton>
              </Box>
            ),
            align: 'right' as const,
          },
        ]}
      />
      {archive.isOpen && (
        <Suspense fallback={null}>
          <ArchivedItemsPanel
            archive={archive}
            deleteFieldModal={deleteFieldModal}
            items={archive.items}
            onBackButtonClick={handleCloseArchivedPanel}
            onCloseButtonClick={handleCloseAllPanels}
            dataHook={dataHook}
          />
        </Suspense>
      )}
    </>
  );
}

export const ArchivedItemsCTAButton = observer(_ArchivedItemsCTAButton);
