import { CustomModalLayout } from '@wix/design-system';
import { getExportModalStepProps } from './getExportModalStepProps';
import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { FiltersMap, useCreateExport } from '@wix/bex-core';
import { ExportButtonModalLayoutProps } from './ExportProps';
import {
  QueryFieldNumber,
  ArrayFieldDelimiter,
} from '@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types';
import { addEventListener } from '@wix/bex-core/util';
import { useIsMobile } from '../../hooks/useIsMobile';
import { CustomDrawerLayout } from '../CustomDrawerLayout';

function _ExportButtonModalLayout<T, F extends FiltersMap>(
  props: ExportButtonModalLayoutProps<T, F>,
) {
  const {
    renderError,
    transformPlatformizedQuery,
    differentQueryEndpointThanCollection,
    customTotal,
    methodMetadata,
    methodSpec,
    fields,
    saveAs,
    exportModalState,
    arrayFieldDelimiter,
    exportModalFooter,
    exportModalTitle,
    onProgressModalTitle,
    exportToCSVMessage,
    ...rest
  } = props;

  const table = useToolbarCollectionContext<T, F>();

  const isMobile = useIsMobile();

  const createExport = useCreateExport<T, F>({
    transformPlatformizedQuery,
    differentQueryEndpointThanCollection,
    customTotal,
    reportBi: table.reportBi,
    exportModalState,
    createExportAsyncJobRequest: {
      methodMetadata,
      fields,
      arrayFieldDelimiter: arrayFieldDelimiter
        ? ArrayFieldDelimiter[arrayFieldDelimiter]
        : undefined,
      methodSpec: methodSpec
        ? {
            ...methodSpec,
            requestQueryFieldNumber: methodSpec.requestQueryFieldNumber
              ? QueryFieldNumber[methodSpec.requestQueryFieldNumber]
              : undefined,
          }
        : undefined,
    },
    saveAs,
  });

  const [state] = useState(() => createExport());

  const { onRequestClose, ...customModalLayoutProps } = getExportModalStepProps(
    {
      state,
      renderError,
      exportModalFooter,
      exportModalTitle,
      onProgressModalTitle,
      exportToCSVMessage,
    },
  );

  useEffect(() => {
    if (onRequestClose) {
      return addEventListener(
        exportModalState.events,
        'requestClose',
        onRequestClose,
      );
    }

    return undefined;
  }, [onRequestClose]);

  useEffect(() => state.init(), []);

  if (isMobile) {
    return (
      <CustomDrawerLayout
        dataHook="export-modal-layout"
        {...rest}
        {...customModalLayoutProps}
      />
    );
  }

  return (
    <CustomModalLayout
      width="510px"
      dataHook="export-modal-layout"
      {...rest}
      {...customModalLayoutProps}
    />
  );
}

export const ExportButtonModalLayout = observer(_ExportButtonModalLayout);
