import Icon from "@ant-design/icons";
import { Popover } from "antd";
import _ from "lodash";
import moment from "moment";
import React, { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { MdFileDownload, MdFileUpload } from "react-icons/md";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import {
  selectScheduleLoad,
  selectScheduleLoadCalculating,
} from "../../redux/application/application.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";
import ScheduleBlockDay from "../schedule-block-day/schedule-block-day.component";
import ScheduleCalendarHeaderGraph from "./schedule-calendar-header-graph.component";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  load: selectScheduleLoad,
  calculating: selectScheduleLoadCalculating,
});

const mapDispatchToProps = (dispatch) => ({});

export function ScheduleCalendarHeaderComponent({
  bodyshop,
  label,
  refetch,
  date,
  load,
  calculating,
  events,
  ...otherProps
}) {
  const ATSToday = useMemo(() => {
    if (!events) return [];
    return _.groupBy(
      events.filter(
        (e) =>
          !e.vacation &&
          e.isintake &&
          moment(date).isSame(moment(e.start), "day")
      ),
      "job.alt_transport"
    );
  }, [events, date]);

  const isDayBlocked = useMemo(() => {
    if (!events) return [];
    return (
      events &&
      events.filter(
        (e) => moment(date).isSame(moment(e.start), "day") && e.block
      )
    );
  }, [events, date]);

  const { t } = useTranslation();
  const loadData = load[date.toISOString().substr(0, 10)];

  const jobsOutPopup = () => (
    <div onClick={(e) => e.stopPropagation()}>
      <table>
        <tbody>
          {loadData && loadData.jobsOut ? (
            loadData.jobsOut.map((j) => (
              <tr key={j.id}>
                <td>
                  <Link to={`/manage/jobs/${j.id}`}>{j.ro_number}</Link>
                </td>
                <td>
                  <OwnerNameDisplay ownerObject={j} />
                </td>
                <td>
                  {`(${(
                    j.labhrs.aggregate.sum.mod_lb_hrs +
                    j.larhrs.aggregate.sum.mod_lb_hrs
                  ).toFixed(1)} ${t("general.labels.hours")})`}
                </td>
                <td>
                  <DateTimeFormatter>
                    {j.scheduled_completion}
                  </DateTimeFormatter>
                </td>
              </tr>
            ))
          ) : (
            <tr>
              <td>{t("appointments.labels.nocompletingjobs")}</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );

  const jobsInPopup = () => (
    <div onClick={(e) => e.stopPropagation()}>
      <table>
        <tbody>
          {loadData && loadData.jobsIn ? (
            loadData.jobsIn.map((j) => (
              <tr key={j.id}>
                <td>
                  <Link to={`/manage/jobs/${j.id}`}>{j.ro_number}</Link>
                </td>
                <td>
                  <OwnerNameDisplay ownerObject={j} />
                </td>
                <td>
                  {`(${(
                    j.labhrs.aggregate.sum.mod_lb_hrs +
                    j.larhrs.aggregate.sum.mod_lb_hrs
                  ).toFixed(1)} ${t("general.labels.hours")})`}
                </td>
                <td>
                  <DateTimeFormatter>{j.scheduled_in}</DateTimeFormatter>
                </td>
              </tr>
            ))
          ) : (
            <tr>
              <td>{t("appointments.labels.noarrivingjobs")}</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );

  const LoadComponent = loadData ? (
    <div>
      <div className="imex-flex-row imex-flex-row__flex-space-around">
        <Popover
          placement={"bottom"}
          content={jobsInPopup}
          trigger="hover"
          title={t("appointments.labels.arrivingjobs")}
        >
          <Icon component={MdFileDownload} style={{ color: "green" }} />
          {(loadData.hoursIn || 0) && loadData.hoursIn.toFixed(2)}
        </Popover>
        <Popover
          placement={"bottom"}
          content={jobsOutPopup}
          trigger="hover"
          title={t("appointments.labels.completingjobs")}
        >
          <Icon component={MdFileUpload} style={{ color: "red" }} />
          {(loadData.hoursOut || 0) && loadData.hoursOut.toFixed(2)}
        </Popover>
        <ScheduleCalendarHeaderGraph loadData={loadData} />
      </div>
      <div>
        <ul style={{ listStyleType: "none", columns: "2 auto", padding: 0 }}>
          {Object.keys(ATSToday).map((key, idx) => (
            <li key={idx}>{`${
              key === "null" || key === "undefined" ? "N/A" : key
            }: ${ATSToday[key].length}`}</li>
          ))}
        </ul>
      </div>
    </div>
  ) : null;

  const isShopOpen = (date) => {
    let day;
    switch (moment(date).day()) {
      case 0:
        day = "sunday";
        break;
      case 1:
        day = "monday";
        break;
      case 2:
        day = "tuesday";
        break;
      case 3:
        day = "wednesday";
        break;
      case 4:
        day = "thursday";
        break;
      case 5:
        day = "friday";
        break;
      case 6:
        day = "saturday";
        break;
      default:
        day = "sunday";
        break;
    }

    return bodyshop.workingdays[day];
  };

  return (
    <div className="imex-calendar-load">
      <ScheduleBlockDay
        alreadyBlocked={isDayBlocked.length > 0}
        date={date}
        refetch={refetch}
      >
        <div style={{ color: isShopOpen(date) ? "" : "tomato" }}>
          {label}
          {calculating ? <LoadingSkeleton /> : LoadComponent}
        </div>
      </ScheduleBlockDay>
    </div>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ScheduleCalendarHeaderComponent);
