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 { DataExtensionState } 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 {
  dataExtension: DataExtensionState;
  onCloseSidePanel: () => void;
  dataHook?: string;
  actionContainerProps?: BoxProps;
}

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

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

  const handleOpenArchivedPanel = useCallback(() => {
    dataExtension?.openArchivedPanel();
  }, [dataExtension]);

  const handleCloseArchivedPanel = useCallback(() => {
    dataExtension?.closeArchivedPanel();
  }, [dataExtension]);

  const handleCloseAllPanels = useCallback(() => {
    dataExtension?.closeArchivedPanel();
    onCloseSidePanel();
  }, [dataExtension, onCloseSidePanel]);

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

export const ArchivedItemsCTAButton = observer(_ArchivedItemsCTAButton);
