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, Modal, Title } from '../../ui/components';
import ModalBody from '../../ui/components/Modal/Body';
import ModalFooter from '../../ui/components/Modal/Footer';
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,
      confirmationTarget = props.confirmationTarget,
      slug = props.slug,
      referenceEnabled = props.referenceEnabled;

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

  var _useState2 = useState({}),
      onboarding = _useState2[0],
      setOnboarding = _useState2[1];

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

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

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

  var _useState6 = useState({}),
      confirmModalState = _useState6[0],
      setConfirmModal = _useState6[1];

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

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

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

  var modalRef = React.createRef();

  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.tutorialOnboarding) setOnboarding(response.tutorialOnboarding);
  }, [response.tutorialOnboarding]);

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

  useEffect(function () {
    if ('moduleEnabled' in response) 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
      });
    });
  };

  var publishTutorial = function publishTutorial(event) {
    var published = event.published;


    modalRef.current.toggle(true);
    return setConfirmModal({
      title: 'Are you sure you want to ' + (published ? 'publish' : 'unpublish') + ' this tutorial?',
      body: published ? 'This will make it viewable all users.' : 'It will no longer be viewable to users.',
      action: ApiActions.updateTutorial.bind(null, initRequest, event),
      buttonText: published ? 'Publish It!' : 'Unpublish Tutorial'
    });
  };

  var deleteTutorial = function deleteTutorial(event) {
    modalRef.current.toggle(true);
    return setConfirmModal({
      title: 'Are you sure you want to delete this tutorial?',
      body: 'You cannot undo this action.',
      action: ApiActions.deleteTutorial.bind(null, initRequest, event),
      buttonText: 'Delete Tutorial'
    });
  };

  var makeHero = function makeHero(event) {
    var _id = event._id,
        published = event.published;


    if (published) return ApiActions.makeHero(initRequest, { _id: _id });

    modalRef.current.toggle(true);
    return setConfirmModal({
      title: 'Are you sure you want to feature an unpublished tutorial?',
      body: 'Featuring an unpublished tutorial will publish it. Make sure it’s ready!',
      action: ApiActions.makeHero.bind(null, initRequest, { _id: _id }),
      buttonText: 'Feature It!'
    });
  };

  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: deleteTutorial,
            makeHero: makeHero,
            numTutorials: tutorials.length,
            openTutorial: openTutorial,
            publish: publishTutorial,
            shiftOrder: function shiftOrder(e) {
              return ApiActions.shiftOrder(initRequest, e);
            },
            tutorial: tutorial
          });
        })
      )
    ),
    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 Tutorials 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,
      endpointOnboarding: onboarding.endpoints,
      open: modalMeta.open,
      referenceEnabled: referenceEnabled,
      requestDataRefresh: function requestDataRefresh() {
        return getTutorials();
      },
      target: modalTarget,
      tutorial: selectedTutorial
    }),
    React.createElement(
      Modal,
      {
        ref: modalRef,
        className: classes.TutorialConfirmation,
        size: 'sm',
        target: confirmationTarget,
        verticalCenter: true
      },
      React.createElement(
        ModalBody,
        null,
        React.createElement(
          Title,
          { className: classes['TutorialConfirmation-Title'], level: 4 },
          confirmModalState.title
        ),
        React.createElement(
          'p',
          { className: classes['TutorialConfirmation-Description'] },
          confirmModalState.body
        )
      ),
      React.createElement(
        ModalFooter,
        { justify: 'center' },
        React.createElement(
          Button,
          {
            bem: { shale_text: true },
            onClick: function onClick() {
              setConfirmModal({});
              modalRef.current.toggle(false);
            }
          },
          'Cancel'
        ),
        React.createElement(
          Button,
          {
            bem: confirmModalState.buttonText === 'Delete Tutorial' ? { red: true } : { blue: true },
            onClick: function onClick() {
              confirmModalState.action();
              modalRef.current.toggle(false);
            }
          },
          confirmModalState.buttonText
        )
      )
    )
  );
}

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

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