import React, { useEffect, useState } from 'react';
import { FiltersMap, ModalState } from '@wix/bex-core';
import { Button, Drawer, Modal } from '@wix/design-system';
import { DownloadImport } from '@wix/wix-ui-icons-common/lazy';
import { observer, Observer } from 'mobx-react-lite';
import { ImportButtonModalLayout } from './ImportButtonModalLayout';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { ImportButtonProps } from './ImportProps';
import { ResponsiveButton } from '../ResponsiveButton/ResponsiveButton';
import { useIsMobile } from '../../hooks/useIsMobile';

function _ImportButton<T, F extends FiltersMap>(props: ImportButtonProps) {
  const { toolbarType = 'default', config, renderFieldEditor } = props;

  const table = useToolbarCollectionContext<T, F>();
  const {
    toolbar: { responsive },
  } = table;

  const { translate: t } = useWixPatternsContainer();
  const [state] = useState(() => (table.importState ??= new ModalState()));
  const isMobile = useIsMobile();

  useEffect(() => {
    table.featuredComponents.importModal.set(
      <Observer>
        {() => {
          const child = (
            <ImportButtonModalLayout
              importModalState={state}
              config={config}
              renderFieldEditor={renderFieldEditor}
            />
          );

          if (isMobile) {
            return (
              <Drawer
                dataHook="import-modal"
                open={state.isOpen}
                onClose={state.requestClose}
              >
                {child}
              </Drawer>
            );
          }

          return (
            <Modal
              onRequestClose={state.requestClose}
              isOpen={state.isOpen}
              dataHook="import-modal"
            >
              {child}
            </Modal>
          );
        }}
      </Observer>,
    );

    return () => {
      table.featuredComponents.importModal.set(null);
    };
  }, []);

  return (
    <div data-hook="import-container">
      {toolbarType === 'default' ? (
        <ResponsiveButton
          state={responsive.actions}
          dataHook="import-button"
          onClick={state.open}
          icon={<DownloadImport />}
        >
          {t('cairo.import.import')}
        </ResponsiveButton>
      ) : (
        <Button
          skin="standard"
          priority="secondary"
          size="small"
          ellipsis
          prefixIcon={<DownloadImport />}
          dataHook="import-button"
          onClick={state.open}
        >
          {t('cairo.import.import')}
        </Button>
      )}
    </div>
  );
}

export const ImportButton = observer(_ImportButton);
