import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { useEffect, useMemo } from "react";
import { useLocation } from "react-router-dom";
import { QUERY_ALL_ACTIVE_APPOINTMENTS } from "../../graphql/appointments.queries";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import { getRange } from "../schedule-calendar-wrapper/schedule-calendar-util";
import ScheduleCalendarComponent from "./schedule-calendar.component";
import { calculateScheduleLoad } from "../../redux/application/application.actions";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import dayjs from "../../utils/day";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  calculateScheduleLoad: (endDate) => dispatch(calculateScheduleLoad(endDate))
});

export function ScheduleCalendarContainer({ calculateScheduleLoad }) {
  const search = queryString.parse(useLocation().search);

  const { date, view } = search;
  const range = useMemo(() => getRange(date, view), [date, view]);

  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ACTIVE_APPOINTMENTS, {
    variables: {
      start: range.start.toDate(),
      end: range.end.toDate(),
      startd: range.start,
      endd: range.end
    },
    skip: !range.start || !range.end,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  useEffect(() => {
    if (data && range.end) calculateScheduleLoad(range.end);
  }, [data, range, calculateScheduleLoad]);

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;
  let normalizedData = [
    ...data.appointments.map((e) => {
      //Required because Hasura returns a string instead of a date object.
      return Object.assign({}, e, { start: new Date(e.start) }, { end: new Date(e.end) });
    }),
    ...data.employee_vacation.map((e) => {
      //Required because Hasura returns a string instead of a date object.
      return {
        ...e,
        title: `${
          (e.employee.first_name && e.employee.first_name.substr(0, 1)) || ""
        } ${e.employee.last_name || ""} OUT`,
        color: "red",
        start: dayjs(e.start).startOf("day").toDate(),
        end: dayjs(e.end).startOf("day").toDate(),
        allDay: true,
        vacation: true
      };
    })
  ];

  return <ScheduleCalendarComponent refetch={refetch} data={data ? normalizedData : []} />;
}

export default connect(mapStateToProps, mapDispatchToProps)(ScheduleCalendarContainer);
