import moment from "moment/moment";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Navigate, useParams } from "react-router-dom";

import { getRequestDates, setRequestDate } from "@redux/reportSlice";

import { apiRequest } from "@api/request";

import { getReports } from "@components/Calendar/calendarHelper";
import { Footer } from "@components/Common/Footer/Footer";
import { Loader } from "@components/Common/Loader/Loader";
import { Navigation } from "@components/Navigation/Navigation";
import { ProfileBreadcrumbs } from "@components/ProfileBreadcrumbs/ProfileBreadcrumbs";
import { ProfileCalendarComponent } from "@components/ProfileCalendar/ProfileCalendarComponent";
import { ProfileHeader } from "@components/ProfileHeader/ProfileHeader";

import "./partnerEmployeeReport.scss";

export const PartnerEmployeeReport = () => {
  // if (
  //   localStorage.getItem("role_status") !== "18"
  // ) {
  //   return <Navigate to="/profile/categories" replace />;
  // }

  const params = useParams();
  const dispatch = useDispatch();
  const [userInfo, setUserInfo] = useState({});
  const [value, setValue] = useState(moment());
  const [reports, setReports] = useState([]);
  const [totalHours, setTotalHours] = useState(0);
  const requestDates = useSelector(getRequestDates);
  const [startRangeDays, setStartRangeDays] = useState(false);
  const [startDate, setStartDate] = useState(null);
  const [loader, setLoader] = useState(true);

  useEffect(() => {
    dispatch(setRequestDate(getReports(moment())));
  }, []);

  useEffect(() => {
    apiRequest(`/resume?userId=${params.uuid}`).then((res) => {
      setUserInfo(res);
    });
  }, []);

  useEffect(() => {
    setLoader(true);
    if (!requestDates) {
      return;
    }
    apiRequest(`/reports/index?${requestDates}&user_id=${params.uuid}`).then(
      (reports) => {
        let spendTime = 0;

        reports
          .filter(
            (item) => new Date(item.created_at).getMonth() === value.month()
          )
          .map((report) => {
            spendTime += report.task.reduce(
              (acc, task) => acc + task.hours_spent,
              0
            );
          });

        setTotalHours(Math.floor(spendTime));
        setReports(reports);
        setLoader(false);
      }
    );
  }, [requestDates]);

  return (
    <div className="employeeReport">
      <ProfileHeader />
      <Navigation />
      <div className="container">
        <ProfileBreadcrumbs
          links={[
            { name: "Главная", link: "/profile" },
            { name: "Данные моего персонала", link: "/profile/employees" }
          ]}
        />
        {!Object.keys(userInfo).length ? (
          <div className="employeeReport__loader">
            <Loader style={"green"} height={80} width={80} />
          </div>
        ) : (
          <>
            <div className="employeeReport__info">
              <div className="employeeReport__name">
                <h2>{userInfo.fio}</h2>
                <p>{userInfo.position}</p>
              </div>
              <div className="employeeReport__skills">
                {userInfo?.stack &&
                  userInfo.stack.map((skill, index) => {
                    return <span key={index}>{skill}</span>;
                  })}
              </div>
            </div>
            <div className="employeeReport__wrapper">
              {loader ? (
                <div className="employeeReport__loader">
                  <Loader style={"green"} height={80} width={80} />
                </div>
              ) : (
                <div className="employeeReport__calendar ">
                  <ProfileCalendarComponent
                    userId={params.uuid}
                    setValueHandler={(value) => setValue(value)}
                    value={value}
                    reports={reports}
                    totalHours={totalHours}
                    startRangeDays={startRangeDays}
                    toggleRangeDays={() => setStartRangeDays(!startRangeDays)}
                    startDate={startDate}
                    setStartDateRange={(date) => setStartDate(date)}
                  />
                </div>
              )}
            </div>
          </>
        )}
      </div>
      <Footer />
    </div>
  );
};
