import React, { Fragment } from 'react';
import { connect } from '../redux/store';
import { compose, lifecycle, withHandlers, withState } from 'recompose';
import { Modal, ModalBody } from 'reactstrap';
import { Utils, openModalForm, StateListWrapper } from '@kineticdata/bundle-common';
import { PageTitle } from './shared/PageTitle';
import { Link } from '@reach/router';
import { actions } from '../redux/modules/appointments';
import { actions as walkInActions } from '../redux/modules/walkIns';
import { enableLocationServices, mapTechBarsForDistance, sortTechBarsByDistance } from '../redux/modules/techBarApp';
import { SESSION_ITEM_USER_LOCATION, SESSION_ITEM_CURRENT_TECH_BAR, DATE_FORMAT, TIME_FORMAT } from '../constants';
import moment from 'moment';
import { I18n, Moment } from '@kineticdata/react';
import heroImage from '../../assets/images/tech-bar-hero.jpg';
export var HomeComponent = function HomeComponent(_ref) {
  var kapp = _ref.kapp,
      techBars = _ref.techBars,
      upcomingAppointments = _ref.upcomingAppointments,
      error = _ref.error,
      modalOpen = _ref.modalOpen,
      setModalOpen = _ref.setModalOpen,
      currentTechBar = _ref.currentTechBar,
      selectCurrentTechBar = _ref.selectCurrentTechBar,
      useLocationServices = _ref.useLocationServices,
      userLocation = _ref.userLocation,
      getUserLocation = _ref.getUserLocation,
      openDropdown = _ref.openDropdown,
      toggleDropdown = _ref.toggleDropdown,
      hasTechBarDisplayRole = _ref.hasTechBarDisplayRole,
      waitingUsers = _ref.waitingUsers;
  var selectedTechBar = currentTechBar || techBars.get(0);
  return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(PageTitle, null), /*#__PURE__*/React.createElement("div", {
    className: "page-container"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-panel"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-panel__header"
  }, /*#__PURE__*/React.createElement("div", {
    className: "hero--tech-bar",
    style: {
      backgroundImage: "url(".concat(heroImage, ")")
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "container"
  }, /*#__PURE__*/React.createElement("div", {
    className: "hero-welcome"
  }, /*#__PURE__*/React.createElement("div", {
    className: "title"
  }, /*#__PURE__*/React.createElement(I18n, null, "Welcome to"), ' ', /*#__PURE__*/React.createElement(I18n, null, selectedTechBar ? selectedTechBar.values['Name'] : kapp ? kapp.name : 'Tech Bar')), /*#__PURE__*/React.createElement("div", {
    className: "subtitle"
  }, selectedTechBar ? /*#__PURE__*/React.createElement(I18n, null, selectedTechBar.values['Description']) : /*#__PURE__*/React.createElement(I18n, null, "We deliver in-person service that gets people back on track."))), selectedTechBar && /*#__PURE__*/React.createElement("div", {
    className: "hero-card"
  }, /*#__PURE__*/React.createElement("div", {
    className: "card"
  }, /*#__PURE__*/React.createElement("div", {
    className: "card__bar card__bar--xs"
  }), /*#__PURE__*/React.createElement("div", {
    className: "card__row flex-grow-1 flex-shrink-1 overflow-auto"
  }, /*#__PURE__*/React.createElement("div", {
    className: "card__row-prepend"
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-map-marker fa-3x"
  })), /*#__PURE__*/React.createElement("div", {
    className: "card__col"
  }, /*#__PURE__*/React.createElement("div", {
    className: "card__row"
  }, /*#__PURE__*/React.createElement("strong", null, /*#__PURE__*/React.createElement(I18n, null, selectedTechBar.values['Name'])), techBars.size > 1 && /*#__PURE__*/React.createElement("button", {
    className: "btn btn-inverse btn-sm ml-auto",
    onClick: function onClick() {
      return setModalOpen(true);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Change"))), selectedTechBar.values['Location'] && /*#__PURE__*/React.createElement("div", {
    className: "card__row-meta text-muted pt-0"
  }, /*#__PURE__*/React.createElement(I18n, null, selectedTechBar.values['Location'])), /*#__PURE__*/React.createElement("div", {
    className: "card__row-meta flex-column flex-grow-1 flex-shrink-1 overflow-auto pt-0 mt-1"
  }, selectedTechBar.values['Details'] && /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement(I18n, null, selectedTechBar.values['Details']))))), /*#__PURE__*/React.createElement("div", {
    className: "card__col pt-0 flex-grow-0 flex-shrink-0"
  }, /*#__PURE__*/React.createElement("div", {
    className: "card__row"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "appointment/".concat(selectedTechBar.values['Id']),
    className: "btn btn-primary flex-grow-1"
  }, /*#__PURE__*/React.createElement(I18n, null, "Schedule Now"), " \u2192")), /*#__PURE__*/React.createElement("div", {
    className: "card__row pt-0"
  }, /*#__PURE__*/React.createElement("div", {
    className: "waiting-users-message ".concat(waitingUsers === 0 ? '' : '')
  }, /*#__PURE__*/React.createElement(I18n, null, "Currently awaiting assistance"), ":", ' ', waitingUsers, ' ', /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return waitingUsers === 1 ? translate('person') : translate('people');
    }
  }))))))))), /*#__PURE__*/React.createElement("div", {
    className: "page-panel__body container"
  }, /*#__PURE__*/React.createElement("section", {
    className: "mt-4"
  }, selectedTechBar ? /*#__PURE__*/React.createElement("div", {
    className: "info-tile__wrapper"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "appointment/".concat(selectedTechBar.values['Id']),
    className: "info-tile"
  }, /*#__PURE__*/React.createElement("div", {
    className: "icon"
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-calendar-o fa-fw"
  })), /*#__PURE__*/React.createElement("div", {
    className: "title"
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-calendar-o fa-fw"
  }), /*#__PURE__*/React.createElement(I18n, null, "Schedule")), /*#__PURE__*/React.createElement("p", {
    className: "description"
  }, /*#__PURE__*/React.createElement(I18n, null, "Schedule an appointment."))), /*#__PURE__*/React.createElement(Link, {
    to: "past",
    className: "info-tile"
  }, /*#__PURE__*/React.createElement("div", {
    className: "icon"
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-clock-o fa-fw"
  })), /*#__PURE__*/React.createElement("div", {
    className: "title"
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-clock-o fa-fw"
  }), /*#__PURE__*/React.createElement(I18n, null, "History")), /*#__PURE__*/React.createElement("p", {
    className: "description"
  }, /*#__PURE__*/React.createElement(I18n, null, "View all of your past appointments."))), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.createElement("div", {
        className: "info-tile actionable",
        onClick: function onClick() {
          return openModalForm({
            formSlug: 'general-feedback',
            kappSlug: kapp.slug,
            values: {
              'Scheduler Id': selectedTechBar.values['Id']
            },
            title: "".concat(translate(selectedTechBar.values['Name']), " ").concat(translate('Feedback')),
            confirmationMessage: translate('Thank you for your feedback.')
          });
        }
      }, /*#__PURE__*/React.createElement("div", {
        className: "icon"
      }, /*#__PURE__*/React.createElement("span", {
        className: "fa fa-comment-o fa-fw"
      })), /*#__PURE__*/React.createElement("div", {
        className: "title"
      }, /*#__PURE__*/React.createElement("span", {
        className: "fa fa-comment-o fa-fw"
      }), /*#__PURE__*/React.createElement(I18n, null, "Feedback")), /*#__PURE__*/React.createElement("p", {
        className: "description"
      }, /*#__PURE__*/React.createElement(I18n, null, "Questions, comments, or concerns.")));
    }
  })) : /*#__PURE__*/React.createElement("div", {
    className: "alert alert-warning alert-bar"
  }, /*#__PURE__*/React.createElement("div", {
    className: "h5"
  }, "There are no Tech Bars configured."), /*#__PURE__*/React.createElement("div", null, "Please contact an administrator."))), /*#__PURE__*/React.createElement("section", {
    className: "mt-4"
  }, /*#__PURE__*/React.createElement("h2", {
    className: "section__title"
  }, /*#__PURE__*/React.createElement(I18n, null, "Upcoming Appointments")), /*#__PURE__*/React.createElement(StateListWrapper, {
    data: upcomingAppointments,
    error: error,
    emptyTitle: "You have no upcoming appointments.",
    emptyMessage: "As you schedule appointments, they'll appear here."
  }, function (data) {
    return /*#__PURE__*/React.createElement("div", {
      className: "cards mb-3"
    }, data.map(function (appt) {
      var techBar = techBars.find(function (t) {
        return t.values['Id'] === appt.values['Scheduler Id'];
      });
      var date = moment.utc(appt.values['Event Date'], DATE_FORMAT);
      var start = moment.utc(appt.values['Event Time'], TIME_FORMAT);
      var end = start.clone().add(appt.values['Event Duration'], 'minute');
      return /*#__PURE__*/React.createElement(Link, {
        to: "appointment/".concat(appt.values['Scheduler Id'], "/").concat(appt.id),
        className: "card",
        key: appt.id
      }, /*#__PURE__*/React.createElement("div", {
        className: "card__row"
      }, /*#__PURE__*/React.createElement("div", {
        className: "card__row-prepend"
      }, /*#__PURE__*/React.createElement("span", {
        className: "fa fa-calendar fa-rounded",
        style: {
          background: 'rgb(255, 74, 94)'
        }
      })), /*#__PURE__*/React.createElement("div", {
        className: "card__col"
      }, /*#__PURE__*/React.createElement("div", {
        className: "card__row-multi"
      }, /*#__PURE__*/React.createElement("div", {
        className: "card__row-subtitle"
      }, /*#__PURE__*/React.createElement(Moment, {
        timestamp: date,
        format: Moment.formats.dateWithDay
      })), /*#__PURE__*/React.createElement("div", {
        className: "card__row text-muted"
      }, /*#__PURE__*/React.createElement(Moment, {
        timestamp: start,
        format: Moment.formats.time
      }), " - ", /*#__PURE__*/React.createElement(Moment, {
        timestamp: end,
        format: Moment.formats.time
      })), /*#__PURE__*/React.createElement("div", {
        className: "card__row-meta"
      }, /*#__PURE__*/React.createElement("strong", null, /*#__PURE__*/React.createElement(I18n, null, techBar.values['Name']))), /*#__PURE__*/React.createElement("div", {
        className: "card__row-meta"
      }, appt.values['Summary']))), /*#__PURE__*/React.createElement("div", {
        className: "card__row-append"
      }, /*#__PURE__*/React.createElement("span", {
        className: "badge badge-pill badge-".concat(appt.coreState === 'Closed' ? 'dark' : 'success')
      }, /*#__PURE__*/React.createElement(I18n, null, appt.values['Status'])))));
    }));
  }))))), modalOpen && /*#__PURE__*/React.createElement(Modal, {
    isOpen: !!modalOpen,
    toggle: function toggle() {
      return setModalOpen(false);
    },
    size: "sm",
    className: "tech-bar-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: function onClick() {
      return setModalOpen(false);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Cancel")), /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(I18n, null, "Location")), /*#__PURE__*/React.createElement(Link, {
    to: "tech-bars",
    className: "btn btn-link"
  }, /*#__PURE__*/React.createElement(I18n, null, "View All")))), useLocationServices && !userLocation && /*#__PURE__*/React.createElement("div", {
    className: "modal-header"
  }, /*#__PURE__*/React.createElement("div", {
    className: "px-3 py-1 text-center"
  }, /*#__PURE__*/React.createElement("button", {
    className: "btn btn-link",
    onClick: getUserLocation
  }, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-fw fa-map-marker"
  }), ' ', /*#__PURE__*/React.createElement(I18n, null, "use my current location")))), /*#__PURE__*/React.createElement(ModalBody, null, /*#__PURE__*/React.createElement("ul", null, techBars.map(function (techBar) {
    return /*#__PURE__*/React.createElement("li", {
      key: techBar.id,
      onClick: function onClick() {
        return selectCurrentTechBar(techBar.id);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "title"
    }, /*#__PURE__*/React.createElement(I18n, null, techBar.values['Name'])), techBar.values['Location'] && /*#__PURE__*/React.createElement("div", {
      className: "subtitle"
    }, /*#__PURE__*/React.createElement(I18n, null, techBar.values['Location'])), userLocation && /*#__PURE__*/React.createElement("div", {
      className: "subtitle"
    }, /*#__PURE__*/React.createElement(I18n, {
      render: function render(translate) {
        return techBar.distance ? "(".concat(techBar.distance.toFixed(1), " ").concat(translate('miles'), ")") : "(".concat(translate('Distance Unknown'), ")");
      }
    })), /*#__PURE__*/React.createElement("div", {
      className: "details"
    }, techBar.values['Description'] && /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement(I18n, null, techBar.values['Description'])), techBar.values['Details'] && /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement(I18n, null, techBar.values['Details']))));
  })))));
};
export var mapStateToProps = function mapStateToProps(state, props) {
  var techBars = state.techBarApp.schedulers.filter(function (s) {
    return s.values['Status'] === 'Active';
  });
  var useLocationServices = enableLocationServices(techBars);
  return {
    kappSlug: state.app.kappSlug,
    kapp: state.app.kapp,
    profile: state.app.profile,
    techBars: useLocationServices && props.userLocation ? techBars.map(mapTechBarsForDistance(props.userLocation)).sort(sortTechBarsByDistance) : techBars,
    error: state.appointments.error,
    upcomingAppointments: state.appointments.upcoming,
    waitingUsers: (state.appointments.overview ? state.appointments.overview.size : 0) + (state.walkIns.overview ? state.walkIns.overview.size : 0),
    useLocationServices: useLocationServices
  };
};
export var mapDispatchToProps = {
  fetchUpcomingAppointmentsRequest: actions.fetchUpcomingAppointmentsRequest,
  fetchAppointmentsOverviewRequest: actions.fetchAppointmentsOverviewRequest,
  fetchWalkInsOverviewRequest: walkInActions.fetchWalkInsOverviewRequest
};

var selectCurrentTechBar = function selectCurrentTechBar(_ref2) {
  var techBars = _ref2.techBars,
      setCurrentTechBar = _ref2.setCurrentTechBar,
      setModalOpen = _ref2.setModalOpen;
  return function (id) {
    setModalOpen(false);
    sessionStorage.setItem(SESSION_ITEM_CURRENT_TECH_BAR, id);
    setCurrentTechBar(techBars.find(function (t) {
      return t.id === id;
    }));
  };
};

var getUserLocation = function getUserLocation(_ref3) {
  var setUserLocation = _ref3.setUserLocation;
  return function () {
    navigator.geolocation.getCurrentPosition(function (position) {
      if (position && position.coords) {
        var userLocObj = {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        };
        setUserLocation(userLocObj);
        sessionStorage.setItem(SESSION_ITEM_USER_LOCATION, JSON.stringify(userLocObj));
      }
    });
  };
};

var toggleDropdown = function toggleDropdown(_ref4) {
  var setOpenDropdown = _ref4.setOpenDropdown,
      openDropdown = _ref4.openDropdown;
  return function (dropdownSlug) {
    return function () {
      return setOpenDropdown(dropdownSlug === openDropdown ? false : dropdownSlug);
    };
  };
};

var hasTechBarDisplayRole = function hasTechBarDisplayRole(_ref5) {
  var profile = _ref5.profile;
  return function (techBarName) {
    return Utils.isMemberOf(profile, "Role::Tech Bar Display::".concat(techBarName));
  };
};

export var Home = compose(withState('userLocation', 'setUserLocation', function () {
  try {
    var locObj = JSON.parse(sessionStorage.getItem(SESSION_ITEM_USER_LOCATION));

    if (locObj && locObj.latitude != null && locObj.longitude != null) {
      return locObj;
    }
  } catch (e) {}

  return null;
}), connect(mapStateToProps, mapDispatchToProps), withState('currentTechBar', 'setCurrentTechBar', function (_ref6) {
  var techBars = _ref6.techBars;
  var techBarId = sessionStorage.getItem(SESSION_ITEM_CURRENT_TECH_BAR);
  return techBarId ? techBars.find(function (t) {
    return t.id === techBarId;
  }) : null;
}), withState('modalOpen', 'setModalOpen', false), withState('openDropdown', 'setOpenDropdown', false), withHandlers({
  selectCurrentTechBar: selectCurrentTechBar,
  getUserLocation: getUserLocation,
  toggleDropdown: toggleDropdown,
  hasTechBarDisplayRole: hasTechBarDisplayRole
}), lifecycle({
  componentDidMount: function componentDidMount() {
    // If not loading, fetch upcoming appointments
    this.props.fetchUpcomingAppointmentsRequest(); // Ask for user location if enabled and not already saved

    if (this.props.useLocationServices && this.props.userLocation === null) {
      this.props.getUserLocation();
    } // Fetch count of checked in customers at the current techbar


    if (this.props.techBars.size > 0) {
      var selectedTechBar = this.props.currentTechBar || this.props.techBars.get(0);
      this.props.fetchAppointmentsOverviewRequest({
        id: selectedTechBar.values['Id']
      });
      this.props.fetchWalkInsOverviewRequest({
        id: selectedTechBar.values['Id']
      });
    }
  },
  componentDidUpdate: function componentDidUpdate(prevProps) {
    if (this.props.techBars.size > 0 && this.props.currentTechBar !== prevProps.currentTechBar) {
      var selectedTechBar = this.props.currentTechBar || this.props.techBars.get(0);
      this.props.fetchAppointmentsOverviewRequest({
        id: selectedTechBar.values['Id']
      });
      this.props.fetchWalkInsOverviewRequest({
        id: selectedTechBar.values['Id']
      });
    }
  }
}))(HomeComponent);