import React, { useState, useCallback, useEffect } from 'react';
import classNames from 'classnames';
import flow from 'lodash/flow';
import { useIntl } from 'react-intl';
import { LoadingIndicator } from '@box/blueprint-web';

// @ts-ignore: no ts definition
// eslint-disable-next-line import/named
import { ORIGIN_DOCGEN_SIDEBAR, SIDEBAR_VIEW_DOCGEN } from '../../../constants';
// @ts-ignore: no ts definition
// eslint-disable-next-line import/named
import { withAPIContext } from '../../common/api-context';
// @ts-ignore: no ts definition
// eslint-disable-next-line import/named
import { withErrorBoundary } from '../../common/error-boundary';
// @ts-ignore: no ts definition
// eslint-disable-next-line import/named
import { withLogger } from '../../common/logger';
import Error from './Error';
import EmptyTags from './EmptyTags';
// @ts-ignore: no ts definition
import SidebarContent from '../SidebarContent';
import TagsSection from './TagsSection';
// @ts-ignore: no ts definition
import messages from './messages';
// @ts-ignore: no ts definition

// @ts-ignore: no ts definition

import commonMessages from '../../common/messages';
import './DocGenSidebar.scss';
import { PDF_FIELD_TAG_TYPES, isPdfFormFieldTagType } from './types';
const DEFAULT_RETRIES = 10;
const PDF_FIELD_TYPE_MESSAGES = {
  checkbox: messages.checkboxTags,
  radiobutton: messages.radiobuttonTags,
  dropdown: messages.dropdownTags
};
const buildJsonPathTree = docGenTags => {
  const pathTree = {};
  docGenTags.forEach(tag => {
    tag.json_paths.forEach(jsonPath => {
      const segments = jsonPath.split('.');
      segments.reduce((node, segment) => {
        if (!node[segment]) node[segment] = {};
        return node[segment];
      }, pathTree);
    });
  });
  return pathTree;
};
const buildDocGenSections = data => {
  const result = [];
  const imageTags = data.filter(tag => tag.tag_type === 'image');
  // anything that is not an image tag or pdf tag would be treated as a text tag
  const textTags = data.filter(tag => tag.tag_type !== 'image' && !isPdfFormFieldTagType(tag.tag_type));
  if (textTags.length > 0) {
    result.push({
      id: 'text',
      message: messages.textTags,
      tree: buildJsonPathTree(textTags)
    });
  }
  if (imageTags.length > 0) {
    result.push({
      id: 'image',
      message: messages.imageTags,
      tree: buildJsonPathTree(imageTags)
    });
  }
  PDF_FIELD_TAG_TYPES.forEach(fieldType => {
    const fieldTags = data.filter(tag => tag.tag_type === fieldType);
    if (fieldTags.length > 0) {
      result.push({
        id: fieldType,
        message: PDF_FIELD_TYPE_MESSAGES[fieldType],
        tree: buildJsonPathTree(fieldTags)
      });
    }
  });
  return result;
};
const DocGenSidebar = ({
  getDocGenTags
}) => {
  const {
    formatMessage
  } = useIntl();
  const [hasError, setHasError] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [sections, setSections] = useState([]);
  const loadTags = useCallback(async (attempts = DEFAULT_RETRIES) => {
    if (attempts <= 0) {
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    try {
      const response = await getDocGenTags();
      if (response?.message) {
        loadTags.call(this, attempts - 1);
      } else if (response?.data) {
        const {
          data
        } = response;
        setSections(buildDocGenSections(data));
        setHasError(false);
        setIsLoading(false);
      } else {
        setHasError(true);
        setIsLoading(false);
      }
    } catch (error) {
      setHasError(true);
      setIsLoading(false);
    }
  },
  // disabling eslint because the getDocGenTags prop is changing very frequently
  // eslint-disable-next-line react-hooks/exhaustive-deps
  []);
  useEffect(() => {
    loadTags(DEFAULT_RETRIES);
  }, [loadTags]);
  const isEmpty = sections.length === 0;
  return /*#__PURE__*/React.createElement(SidebarContent, {
    sidebarView: SIDEBAR_VIEW_DOCGEN,
    title: formatMessage(messages.docGenTags)
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('bcs-DocGenSidebar', {
      center: isEmpty || hasError || isLoading
    })
  }, hasError && /*#__PURE__*/React.createElement(Error, {
    onClick: () => loadTags(DEFAULT_RETRIES)
  }), isLoading && /*#__PURE__*/React.createElement(LoadingIndicator, {
    "aria-label": formatMessage(commonMessages.loading),
    className: "bcs-DocGenSidebar-loading"
  }), !hasError && !isLoading && isEmpty && /*#__PURE__*/React.createElement(EmptyTags, null), !hasError && !isLoading && !isEmpty && /*#__PURE__*/React.createElement(React.Fragment, null, sections.map(section => /*#__PURE__*/React.createElement(TagsSection, {
    key: section.id,
    message: section.message,
    data: section.tree
  })))));
};
export { DocGenSidebar as DocGenSidebarComponent };
export default flow([withLogger(ORIGIN_DOCGEN_SIDEBAR), withErrorBoundary(ORIGIN_DOCGEN_SIDEBAR), withAPIContext])(DocGenSidebar);
//# sourceMappingURL=DocGenSidebar.js.map