import { Col, Row, Spin } from "antd";
import { useEffect, useState } from "react";
import ScoreboardChart from "../scoreboard-chart/scoreboard-chart.component";
import ScoreboardLastDays from "../scoreboard-last-days/scoreboard-last-days.component";
import ScoreboardTargetsTable from "../scoreboard-targets-table/scoreboard-targets-table.component";
import { useApolloClient, useQuery } from "@apollo/client/react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { GET_BLOCKED_DAYS, QUERY_SCOREBOARD } from "../../graphql/scoreboard.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import dayjs from "../../utils/day";
import {
  clearHolidays,
  clearWorkingWeekdays,
  setHolidays,
  setWorkingWeekdays
} from "../scoreboard-targets-table/scoreboard-targets-table.util";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({});
export default connect(mapStateToProps, mapDispatchToProps)(ScoreboardDisplayComponent);

export function ScoreboardDisplayComponent({ bodyshop }) {
  const scoreboardSubscription = useQuery(QUERY_SCOREBOARD, {
    variables: {
      start: dayjs().startOf("month"),
      end: dayjs().endOf("month")
    },
    pollInterval: 60000 * 5
  });

  const { data } = scoreboardSubscription;
  const client = useApolloClient();
  const scoreBoardlist = data?.scoreboard || [];
  const sbEntriesByDate = {};

  scoreBoardlist.forEach((i) => {
    const entryDate = i.date;
    if (!sbEntriesByDate[entryDate]) {
      sbEntriesByDate[entryDate] = [];
    }
    sbEntriesByDate[entryDate].push(i);
  });

  const [loading, setLoading] = useState(true); // Loading state

  useEffect(() => {
    async function setDayJSSettings() {
      try {
        let appointments;

        if (!bodyshop.scoreboard_target.ignoreblockeddays) {
          const { data } = await client.query({
            query: GET_BLOCKED_DAYS,
            variables: {
              start: dayjs().startOf("month"),
              end: dayjs().endOf("month")
            }
          });
          appointments = data.appointments;
        }

        const holidays = appointments ? appointments.map((h) => dayjs(h.start).format("MM-DD-YYYY")) : [];
        const workingWeekdays = translateSettingsToWorkingDays(bodyshop.workingdays);

        // Set holidays and working weekdays
        setHolidays(holidays);
        setWorkingWeekdays(workingWeekdays);
      } finally {
        setLoading(false); // Set loading to false after processing
      }
    }

    setDayJSSettings();

    // Cleanup on unmount
    return () => {
      clearHolidays();
      clearWorkingWeekdays();
    };
  }, [client, bodyshop]);

  if (loading) {
    return (
      <Row justify="center" align="middle" style={{ minHeight: "100vh" }}>
        <Spin size="large" />
      </Row>
    );
  }

  return (
    <Row gutter={[16, 16]}>
      <Col span={24}>
        <ScoreboardTargetsTable scoreBoardlist={scoreBoardlist} />
      </Col>
      <Col span={24}>
        <ScoreboardLastDays sbEntriesByDate={sbEntriesByDate} />
      </Col>
      <Col span={24}>
        <ScoreboardChart sbEntriesByDate={sbEntriesByDate} />
      </Col>
    </Row>
  );
}

function translateSettingsToWorkingDays(workingdays) {
  const days = [];
  if (workingdays.monday) days.push(1);
  if (workingdays.tuesday) days.push(2);
  if (workingdays.wednesday) days.push(3);
  if (workingdays.thursday) days.push(4);
  if (workingdays.friday) days.push(5);
  if (workingdays.saturday) days.push(6);
  if (workingdays.sunday) days.push(0);
  return days;
}
