import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import React from 'react';
import { connect } from '../redux/store';
import { compose, withHandlers, withState, withProps } from 'recompose';
import { DisplayTabs } from './Display';
import { Modal, ModalBody, ModalFooter } from 'reactstrap';
import { createSubmission } from '@kineticdata/react';
import { selectCurrentKapp, addToastAlert } from '@kineticdata/bundle-common';
import { TIME_FORMAT } from '../constants';
import { actions as appointmentActions } from '../redux/modules/appointments';
import { actions as walkInActions } from '../redux/modules/walkIns';
import { I18n, Moment } from '@kineticdata/react';
import moment from 'moment';
var FEEDBACK_FORM_SLUG = 'feedback';
export var FeedbackComponent = function FeedbackComponent(_ref) {
  var crosslink = _ref.crosslink,
      techBarId = _ref.techBarId,
      loading = _ref.loading,
      getFilteredAppointments = _ref.getFilteredAppointments,
      handleExperienceClick = _ref.handleExperienceClick,
      experience = _ref.experience,
      input = _ref.input,
      setInput = _ref.setInput,
      appointment = _ref.appointment,
      setAppointment = _ref.setAppointment,
      disabled = _ref.disabled,
      feedbackIdentityRequired = _ref.feedbackIdentityRequired,
      resetExperience = _ref.resetExperience,
      handleSubmitFeedback = _ref.handleSubmitFeedback;
  var filteredAppointments = experience && input.length > 2 ? getFilteredAppointments() : null;
  return /*#__PURE__*/React.createElement("section", {
    className: "tech-bar-display tech-bar-display--feedback"
  }, /*#__PURE__*/React.createElement("div", {
    className: "full-screen-container"
  }, crosslink && /*#__PURE__*/React.createElement(DisplayTabs, {
    techBarId: techBarId,
    feedbackClassName: 'bg-dark'
  }), /*#__PURE__*/React.createElement("div", {
    className: "header bg-dark"
  }), /*#__PURE__*/React.createElement("div", {
    className: "body"
  }, /*#__PURE__*/React.createElement("div", {
    className: "form"
  }, /*#__PURE__*/React.createElement("h1", null, /*#__PURE__*/React.createElement(I18n, null, "How was your experience?")), /*#__PURE__*/React.createElement("div", {
    className: "experience-options"
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "btn btn-success",
    disabled: disabled,
    onClick: function onClick() {
      return handleExperienceClick('Positive');
    }
  }, /*#__PURE__*/React.createElement("span", {
    className: "sr-only"
  }, "Postive"), /*#__PURE__*/React.createElement("span", {
    className: "fa fa-smile-o"
  })), /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "btn btn-danger",
    disabled: disabled,
    onClick: function onClick() {
      return handleExperienceClick('Negative');
    }
  }, /*#__PURE__*/React.createElement("span", {
    className: "sr-only"
  }, "Negative"), /*#__PURE__*/React.createElement("span", {
    className: "fa fa-frown-o"
  })))))), experience && /*#__PURE__*/React.createElement(Modal, {
    isOpen: !!experience,
    toggle: resetExperience,
    size: "md",
    className: "feedback-identity-modal"
  }, /*#__PURE__*/React.createElement("div", {
    className: "modal-header"
  }, /*#__PURE__*/React.createElement("h4", {
    className: "modal-title"
  }, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "btn btn-link",
    onClick: resetExperience
  }, /*#__PURE__*/React.createElement(I18n, null, "Cancel")), /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(I18n, null, "Tell Us Who You Are")))), /*#__PURE__*/React.createElement(ModalBody, {
    className: "modal-body--padding"
  }, /*#__PURE__*/React.createElement("div", {
    className: "form"
  }, /*#__PURE__*/React.createElement("div", {
    className: "form-group ".concat(feedbackIdentityRequired ? 'required' : '')
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: "appointment-search-input"
  }, /*#__PURE__*/React.createElement(I18n, null, "Find Your Appointment by Name or Email"), feedbackIdentityRequired ? /*#__PURE__*/React.createElement("span", {
    className: "text-danger"
  }, "*") : /*#__PURE__*/React.createElement("span", null, ' ', "(", /*#__PURE__*/React.createElement(I18n, null, "Optional"), ")")), /*#__PURE__*/React.createElement("input", {
    type: "text",
    name: "appointment-search-input",
    id: "appointment-search-input",
    className: "form-control",
    autoComplete: "off",
    value: input,
    onChange: function onChange(e) {
      setInput(e.target.value);
      setAppointment(null);
    }
  })), filteredAppointments && /*#__PURE__*/React.createElement("div", {
    className: "form-group"
  }, filteredAppointments.map(function (appt) {
    return /*#__PURE__*/React.createElement("div", {
      className: "tech-bar-appointment-card ".concat(appointment && appointment.id === appt.id ? 'selected' : ''),
      key: appt.id
    }, /*#__PURE__*/React.createElement("div", {
      className: "details"
    }, /*#__PURE__*/React.createElement("div", null, appt.displayName, ' ', /*#__PURE__*/React.createElement("span", {
      className: "text-muted"
    }, "(", /*#__PURE__*/React.createElement(I18n, null, appt.type), ")")), /*#__PURE__*/React.createElement("div", {
      className: "text-muted"
    }, /*#__PURE__*/React.createElement(Moment, {
      timestamp: moment(appt.eventTime, TIME_FORMAT),
      format: Moment.formats.time
    }), ' - ', /*#__PURE__*/React.createElement(I18n, null, appt.eventType))), (!appointment || appointment.id !== appt.id) && /*#__PURE__*/React.createElement("button", {
      type: "button",
      className: "btn btn-primary",
      onClick: function onClick() {
        return setAppointment(appt);
      }
    }, /*#__PURE__*/React.createElement(I18n, null, "Select")));
  }), filteredAppointments.size === 0 && (loading ? /*#__PURE__*/React.createElement("div", {
    className: "text-center"
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-spinner fa-spin"
  })) : /*#__PURE__*/React.createElement("div", {
    className: "alert alert-warning text-center"
  }, /*#__PURE__*/React.createElement(I18n, null, "No appointments found.")))))), /*#__PURE__*/React.createElement(ModalFooter, null, /*#__PURE__*/React.createElement("button", {
    type: "button",
    className: "btn btn-primary",
    disabled: feedbackIdentityRequired && !appointment,
    onClick: function onClick() {
      return handleSubmitFeedback();
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Submit Feedback")))));
};
export var mapStateToProps = function mapStateToProps(state, props) {
  return {
    kapp: selectCurrentKapp(state),
    loading: !state.appointments.today || !state.walkIns.today,
    errors: [state.appointments.error, state.walkIns.error].filter(function (e) {
      return e;
    }),
    appointments: state.appointments.today,
    walkIns: state.walkIns.today,
    records: (state.appointments.today || []).map(function (a) {
      return {
        id: a.id,
        type: 'Appointment',
        username: a.values['Requested For'],
        displayName: a.values['Requested For Display Name'],
        schedulerId: a.values['Scheduler Id'],
        eventType: a.values['Event Type'],
        eventDate: a.values['Event Date'],
        eventTime: a.values['Event Time']
      };
    }).concat((state.walkIns.today || []).map(function (w) {
      return {
        id: w.id,
        type: 'Walk-In',
        username: w.values['Requested For'] || w.values['Email'],
        displayName: w.values['Requested For Display Name'] || "".concat(w.values['First Name'], " ").concat(w.values['Last Name']),
        schedulerId: w.values['Scheduler Id'],
        eventType: w.values['Event Type'],
        eventDate: w.values['Date'],
        eventTime: w.values['Time']
      };
    }))
  };
};
export var mapDispatchToProps = {
  fetchTodayAppointmentsRequest: appointmentActions.fetchTodayAppointmentsRequest,
  fetchTodayWalkInsRequest: walkInActions.fetchTodayWalkInsRequest
};

var getFilteredAppointments = function getFilteredAppointments(_ref2) {
  var input = _ref2.input,
      records = _ref2.records;
  return function () {
    return records.filter(function (appt) {
      return appt.username.toLowerCase().includes(input.toLowerCase()) || appt.displayName.toLowerCase().includes(input.toLowerCase());
    });
  };
};

var resetExperience = function resetExperience(_ref3) {
  var experience = _ref3.experience,
      setExperience = _ref3.setExperience,
      input = _ref3.input,
      setInput = _ref3.setInput;
  return function () {
    setExperience('');
    setInput('');
  };
};

var handleExperienceClick = function handleExperienceClick(_ref4) {
  var feedbackIdentityAvailable = _ref4.feedbackIdentityAvailable,
      setExperience = _ref4.setExperience,
      handleSubmitFeedback = _ref4.handleSubmitFeedback,
      techBarId = _ref4.techBarId,
      fetchTodayAppointmentsRequest = _ref4.fetchTodayAppointmentsRequest,
      fetchTodayWalkInsRequest = _ref4.fetchTodayWalkInsRequest;
  return function (value) {
    if (feedbackIdentityAvailable) {
      setExperience(value);
      fetchTodayAppointmentsRequest({
        schedulerId: techBarId
      });
      fetchTodayWalkInsRequest({
        schedulerId: techBarId
      });
    } else {
      handleSubmitFeedback({
        Experience: value
      });
    }
  };
};

var handleSubmitFeedback = function handleSubmitFeedback(_ref5) {
  var kapp = _ref5.kapp,
      techBarId = _ref5.techBarId,
      experience = _ref5.experience,
      appointment = _ref5.appointment,
      resetExperience = _ref5.resetExperience,
      setDisabled = _ref5.setDisabled;
  return function (values) {
    createSubmission({
      kappSlug: kapp.slug,
      formSlug: FEEDBACK_FORM_SLUG,
      values: values ? _objectSpread(_objectSpread({}, values), {}, {
        'Scheduler Id': techBarId
      }) : _objectSpread({
        Experience: experience,
        'Scheduler Id': techBarId
      }, appointment ? {
        'Appointment Id': appointment.id,
        'Event Type': appointment.eventType,
        'Event Date': appointment.eventDate
      } : {}),
      completed: true
    }).then(function (_ref6) {
      var submission = _ref6.submission,
          error = _ref6.error;

      if (error) {
        addToastAlert({
          message: 'There was an error while submitting your feedback. Please consult an administrator.',
          duration: 5000
        });
      } else {
        addToastAlert({
          title: 'Thank You',
          message: 'Your feedback has been submitted.',
          severity: 'success',
          duration: 4000
        });
        setDisabled(true);
        setTimeout(function () {
          return setDisabled(false);
        }, 4000);
      }

      resetExperience();
    });
  };
};

export var Feedback = compose(connect(mapStateToProps, mapDispatchToProps), withProps(function (_ref7) {
  var techBar = _ref7.techBar,
      kapp = _ref7.kapp;
  return {
    techBarId: techBar.values['Id'],
    feedbackIdentityAvailable: techBar.settings.feedbackIdentitifcation !== 'Hidden',
    feedbackIdentityRequired: techBar.settings.feedbackIdentitifcation === 'Required'
  };
}), withState('experience', 'setExperience', null), withState('input', 'setInput', ''), withState('appointment', 'setAppointment', null), withState('disabled', 'setDisabled', false), withHandlers({
  resetExperience: resetExperience
}), withHandlers({
  getFilteredAppointments: getFilteredAppointments,
  handleSubmitFeedback: handleSubmitFeedback
}), withHandlers({
  handleExperienceClick: handleExperienceClick
}))(FeedbackComponent);