import { Drawer, Modal } from '@wix/design-system';
import React, { useState } from 'react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { FiltersMap, ModalState } from '@wix/bex-core';
import { ExportButtonModalLayout } from './ExportButtonModalLayout';
import { observer } from 'mobx-react-lite';
import { ExportModalProps } from './ExportProps';
import { useIsMobile } from '../../hooks/useIsMobile';

function _ExportModal<T, F extends FiltersMap>(props: ExportModalProps<T, F>) {
  const table = useToolbarCollectionContext<T, F>();

  const [exportModalState] = useState(
    () => (table.exportState ??= new ModalState()),
  );

  const isMobile = useIsMobile();

  const child = (
    <ExportButtonModalLayout {...props} exportModalState={exportModalState} />
  );

  if (isMobile) {
    return (
      <Drawer
        dataHook="export-modal"
        open={exportModalState.isOpen}
        onClose={exportModalState.close}
      >
        {child}
      </Drawer>
    );
  }

  return (
    <Modal
      onRequestClose={exportModalState.close}
      isOpen={exportModalState.isOpen}
      dataHook="export-modal"
    >
      {child}
    </Modal>
  );
}

export const ExportModal = observer(_ExportModal);
