import dayjs from "../../utils/day";
import queryString from "query-string";
import React from "react";
import { Calendar } from "react-big-calendar";
import { connect } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import Event from "../job-at-change/schedule-event.container";
import HeaderComponent from "./schedule-calendar-header.component";
import "./schedule-calendar.styles.scss";
import JobDetailCards from "../job-detail-cards/job-detail-cards.component";
import { selectProblemJobs } from "../../redux/application/application.selectors";
import { Alert, Collapse, Space } from "antd";
import { Trans, useTranslation } from "react-i18next";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import local from "./localizer";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  problemJobs: selectProblemJobs
});

const localizer = local(dayjs);

export function ScheduleCalendarWrapperComponent({
  bodyshop,
  problemJobs,
  data,
  refetch,
  defaultView,
  setDateRangeCallback,
  date,
  ...otherProps
}) {
  const search = queryString.parse(useLocation().search);
  const history = useNavigate();
  const { t } = useTranslation();
  const handleEventPropStyles = (event, start, end, isSelected) => {
    return {
      ...(event.color && !((search.view || defaultView) === "agenda")
        ? {
            style: {
              backgroundColor: event.color && event.color.hex ? event.color.hex : event.color
            }
          }
        : {}),
      className: `${event.arrived ? "imex-event-arrived" : ""} ${event.block ? "imex-event-block" : ""}`
    };
  };

  const selectedDate = new Date(date || dayjs(search.date) || Date.now());

  return (
    <>
      <JobDetailCards />
      {InstanceRenderManager({
        imex:
          problemJobs && problemJobs.length > 2 ? (
            <Collapse style={{ marginBottom: "5px" }}>
              <Collapse.Panel
                key="1"
                header={<span style={{ color: "tomato" }}>{t("appointments.labels.severalerrorsfound")}</span>}
              >
                <Space direction="vertical" style={{ width: "100%" }}>
                  {problemJobs.map((problem) => (
                    <Alert
                      key={problem.id}
                      type="error"
                      message={
                        <Trans
                          i18nKey="appointments.labels.dataconsistency"
                          components={[<Link to={`/manage/jobs/${problem.id}`} target="_blank" />]}
                          values={{
                            ro_number: problem.ro_number,
                            code: problem.code
                          }}
                        />
                      }
                    />
                  ))}
                </Space>
              </Collapse.Panel>
            </Collapse>
          ) : (
            <Space direction="vertical" style={{ width: "100%", marginBottom: "5px" }}>
              {problemJobs.map((problem) => (
                <Alert
                  key={problem.id}
                  type="error"
                  message={
                    <Trans
                      i18nKey="appointments.labels.dataconsistency"
                      components={[<Link to={`/manage/jobs/${problem.id}`} target="_blank" />]}
                      values={{
                        ro_number: problem.ro_number,
                        code: problem.code
                      }}
                    />
                  }
                />
              ))}
            </Space>
          ),

        rome: "USE_IMEX",
        promanager: <span />
      })}

      <Calendar
        events={data}
        defaultView={search.view || defaultView || "week"}
        date={selectedDate}
        onNavigate={(date, view, action) => {
          search.date = date.toISOString().substr(0, 10);
          history({ search: queryString.stringify(search) });
        }}
        onRangeChange={(start, end) => {
          if (setDateRangeCallback) setDateRangeCallback({ start, end });
        }}
        onView={(view) => {
          search.view = view;
          history({ search: queryString.stringify(search) });
        }}
        step={15}
        // timeslots={1}
        showMultiDayTimes
        localizer={localizer}
        min={bodyshop.schedule_start_time ? new Date(bodyshop.schedule_start_time) : new Date("2020-01-01T06:00:00")}
        max={bodyshop.schedule_end_time ? new Date(bodyshop.schedule_end_time) : new Date("2020-01-01T20:00:00")}
        eventPropGetter={handleEventPropStyles}
        components={{
          event: (e) => Event({ bodyshop: bodyshop, event: e.event, refetch: refetch }),
          header: (p) => <HeaderComponent {...p} events={data} refetch={refetch} />
        }}
        {...otherProps}
      />
    </>
  );
}

export default connect(mapStateToProps, null)(ScheduleCalendarWrapperComponent);
