var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

// 3rd-party libs
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import cloneDeep from 'lodash/cloneDeep';

// Internals
import * as ApiActions from './apiActions';
import useReadmeApi from '../../core/hooks/useReadmeApi';

// Components
import { Button, Toggle, Notification } from '../../ui/components';
import TutorialHero from './components/TutorialHero';
import TutorialCard from '../../ui/compositions/TutorialCard';
import TutorialModal from '../../ui/compositions/TutorialModal';
import TutorialObstacle from '../../ui/compositions/TutorialObstacle';

// Constants
import { DEFAULT_TUTORIAL } from '../../ui/compositions/TutorialModal/constants/stepDefaults';

// Style
import classes from './style.module.scss';

export var PermissionContext = React.createContext(false);

export default function Tutorials(props) {
  var baseUrl = props.baseUrl,
      modalTarget = props.modalTarget,
      slug = props.slug,
      referenceEnabled = props.referenceEnabled;

  var _useState = useState({}),
      hero = _useState[0],
      setHero = _useState[1];

  var _useState2 = useState([]),
      tutorials = _useState2[0],
      setTutorials = _useState2[1];

  var _useState3 = useState(true),
      initialLoad = _useState3[0],
      setInitialLoad = _useState3[1];

  var _useState4 = useState({
    open: false,
    action: 'View'
  }),
      modalMeta = _useState4[0],
      setModalMeta = _useState4[1];

  var _useState5 = useState(false),
      moduleEnabled = _useState5[0],
      setModuleEnabled = _useState5[1];

  var _useState6 = useState(),
      selectedTutorial = _useState6[0],
      setSelectedTutorial = _useState6[1];

  var _useState7 = useState(props.isAdmin),
      isAdmin = _useState7[0];

  var _useReadmeApi = useReadmeApi(baseUrl),
      response = _useReadmeApi.response,
      error = _useReadmeApi.error,
      setError = _useReadmeApi.setError,
      pendingRequest = _useReadmeApi.pendingRequest,
      initRequest = _useReadmeApi.initRequest;

  var getTutorials = function getTutorials() {
    return ApiActions.getTutorials(initRequest);
  };

  useEffect(function () {
    getTutorials();
  }, []);

  useEffect(function () {
    if (pendingRequest) getTutorials();
  }, [pendingRequest]);

  useEffect(function () {
    if (Object.keys(response).length) setInitialLoad(false);
  }, [response]);

  useEffect(function () {
    if (response.hero) setHero(response.hero);
  }, [response.hero]);

  useEffect(function () {
    if (response.tutorials) setTutorials(response.tutorials);
  }, [response.tutorials]);

  useEffect(function () {
    if (response.moduleEnabled) setModuleEnabled(response.moduleEnabled);
  }, [response.moduleEnabled]);

  useEffect(function () {
    if (slug) {
      ApiActions.getTutorialBySlug(initRequest, { slug: slug });
      setTimeout(function () {
        return getTutorials();
      });
    }
  }, [slug]);

  useEffect(function () {
    if (response.tutorial && !response.tutorialPublishToggled) {
      setSelectedTutorial(response.tutorial);
      setModalMeta({
        open: true,
        action: 'View'
      });
    }
  }, [response.tutorial]);

  var pushState = function pushState(pathSlug) {
    var urlRegexp = /https?:\/\//;
    if (!urlRegexp.test(baseUrl)) {
      var uri = pathSlug ? baseUrl + '/tutorials/' + pathSlug : baseUrl + '/tutorials';
      // eslint-disable-next-line no-restricted-globals
      history.pushState('', '', uri);
    }
  };

  var openTutorial = function openTutorial(action, id) {
    setModalMeta({
      open: true,
      action: action
    });
    // Allow us to differentiate based on two factors
    // What type of modal action is this? View|Create|Update
    // And is this the first time we're opening it?
    setSelectedTutorial(function (prevTutorial) {
      var prevId = prevTutorial && prevTutorial._id && prevTutorial._id.toString();
      var newId = id && id.toString() || '';

      if (prevId !== newId && action === 'Create') {
        return _extends({}, cloneDeep(DEFAULT_TUTORIAL));
      } else if (prevId !== newId) {
        var tutorial = tutorials.find(function (tut) {
          return tut._id.toString() === newId;
        });
        pushState(tutorial.slug);
        return _extends({}, tutorial);
      }
      // If we're opening the same modal, we don't want to overwrite any previous work
      return prevTutorial;
    });
  };

  var closeTutorialModal = function closeTutorialModal() {
    pushState();
    setModalMeta(function (prevMeta) {
      return _extends({}, prevMeta, {
        open: false
      });
    });
  };

  return React.createElement(
    PermissionContext.Provider,
    { value: isAdmin },
    !initialLoad && !tutorials.length && React.createElement(
      TutorialObstacle,
      {
        body: 'Tutorials are task-driven guidance for your API. Try creating a new Tutorial for your users!',
        className: modalMeta.open && 'paused',
        heading: 'Create a Tutorial to Get Started'
      },
      React.createElement(
        Button,
        { onClick: function onClick() {
            return openTutorial('Create');
          } },
        'Create Tutorial'
      ),
      React.createElement(
        Button,
        { bem: { shale: true } },
        'Try Example'
      )
    ),
    tutorials.length > 0 && React.createElement(
      React.Fragment,
      null,
      hero && hero.title && React.createElement(TutorialHero, { hero: hero, openTutorial: openTutorial }),
      React.createElement(
        'section',
        { className: classes.TutorialGrid },
        tutorials.map(function (tutorial, idx) {
          return React.createElement(TutorialCard, {
            key: 'tut-' + idx,
            className: classes['TutorialGrid-Card'],
            deleteTutorial: function deleteTutorial(e) {
              return ApiActions.deleteTutorial(initRequest, e);
            },
            makeHero: function makeHero(e) {
              return ApiActions.makeHero(initRequest, e);
            },
            numTutorials: tutorials.length,
            openTutorial: openTutorial,
            shiftOrder: function shiftOrder(e) {
              return ApiActions.shiftOrder(initRequest, e);
            },
            tutorial: tutorial,
            updateTutorial: function updateTutorial(e) {
              return ApiActions.updateTutorial(initRequest, e);
            }
          });
        })
      )
    ),
    isAdmin && React.createElement(
      'div',
      { className: classes.TutorialToolbar },
      React.createElement(
        'div',
        {
          'data-tooltip': !tutorials.length ? 'The Tutorial view won’t be shown until you create your first tutorial.' : '',
          'data-tooltip-position': 'top'
        },
        React.createElement(Toggle, {
          checked: moduleEnabled,
          disabled: !tutorials.length,
          label: 'Show Tutorial Page in Navigation',
          onChange: function onChange() {
            return ApiActions.toggleModule(initRequest);
          },
          type: 'toggle'
        })
      ),
      React.createElement(
        Button,
        {
          bem: { blue: true },
          circular: true,
          className: classes['TutorialToolbar-Button'],
          onClick: function onClick() {
            return openTutorial('Create');
          }
        },
        'Create Tutorial'
      )
    ),
    isAdmin && error && React.createElement(
      Notification,
      { color: 'red', dismissible: true, handleClick: function handleClick() {
          return setError(null);
        }, position: 'top' },
      React.createElement(
        'p',
        null,
        error
      )
    ),
    React.createElement(TutorialModal, {
      action: modalMeta.action,
      baseUrl: baseUrl,
      closeTutorialModal: closeTutorialModal,
      open: modalMeta.open,
      referenceEnabled: referenceEnabled,
      requestDataRefresh: function requestDataRefresh() {
        return getTutorials();
      },
      target: modalTarget,
      tutorial: selectedTutorial
    })
  );
}

Tutorials.propTypes = process.env.NODE_ENV !== "production" ? {
  baseUrl: PropTypes.string,
  isAdmin: PropTypes.bool.isRequired,
  modalTarget: PropTypes.string,
  referenceEnabled: PropTypes.bool,
  slug: PropTypes.string
} : {};

Tutorials.defaultProps = {
  baseUrl: '',
  isAdmin: false,
  modalTarget: '#modal-root',
  referenceEnabled: false
};