import ScheduleDayViewComponent from "./schedule-day-view.component";
import { useQuery } from "@apollo/client/react";
import { QUERY_APPOINTMENT_BY_DATE } from "../../graphql/appointments.queries";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import dayjs from "../../utils/day";
import { useTranslation } from "react-i18next";

export default function ScheduleDayViewContainer({ day }) {
  const { loading, error, data } = useQuery(QUERY_APPOINTMENT_BY_DATE, {
    variables: {
      start: dayjs(day).startOf("day"),
      end: dayjs(day).endOf("day"),
      startd: dayjs(day).startOf("day").format("YYYY-MM-DD"),
      endd: dayjs(day).add(1, "day").format("YYYY-MM-DD")
    },
    skip: !dayjs(day).isValid(),
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });
  const { t } = useTranslation();
  if (!day) return <div>{t("appointments.labels.nodateselected")}</div>;
  if (loading) return <LoadingSkeleton paragraph={{ rows: 4 }} />;
  if (error) return <div>{error.message}</div>;
  let normalizedData;

  if (data) {
    normalizedData = [
      ...data.appointments.map((e) => {
        //Required becuase 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 becuase 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(),
          vacation: true
        };
      })
    ];
  }

  return <ScheduleDayViewComponent data={data ? normalizedData : []} day={day} />;
}
