import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

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

import {
  getCorrectDate,
  getCreatedDate,
  hourOfNum
} 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 { ProfileHeader } from "@components/ProfileHeader/ProfileHeader";

import arrowSwitchDate from "assets/icons/arrows/arrowViewReport.png";
import arrow from "assets/icons/arrows/left-arrow.png";

import "./viewReport.scss";

export const ViewReport = () => {
  const params = useParams();
  const [previousReportDay] = useState(new Date(params.date));
  const [nextReportDay] = useState(new Date(params.date));

  const [taskText, setTaskText] = useState([]);
  const [difficulties, setDifficulties] = useState([]);
  const [tomorrowTask, setTomorrowTask] = useState([]);
  const [taskId, setTaskId] = useState("");
  const [totalHours, setTotalHours] = useState(0);
  const [currentDay] = useState(new Date());
  const [loader, setLoader] = useState(false);
  const [deleteLoader, setDeleteLoader] = useState(false);

  function getReportFromDate(day) {
    setLoader(true);
    setTaskText([]);
    setDifficulties([]);
    setTomorrowTask([]);
    apiRequest(`reports/find-by-date?user_id=${params.id}&date=${day}`).then(
      (res) => {
        let spendTime = 0;
        setTaskId(res[0]?.id);
        for (const item of res) {
          if (item.difficulties) {
            setDifficulties((prevArray) => [...prevArray, item.difficulties]);
          }
          if (item.tomorrow) {
            setTomorrowTask((prevArray) => [...prevArray, item.tomorrow]);
          }
          item.task.map((task) => {
            const taskInfo = {
              hours: task.hours_spent,
              task: task.task,
              id: task.id
            };
            spendTime += Math.floor(task.hours_spent);

            setTaskText((prevArray) => [...prevArray, taskInfo]);
          });
        }
        setTotalHours(Math.floor(spendTime));
        setLoader(false);
      }
    );
    previousReportDay.setDate(previousReportDay.getDate() - 1);
    nextReportDay.setDate(nextReportDay.getDate() + 1);
  }

  function deleteReport() {
    setDeleteLoader(true);
    apiRequest(`reports/delete?id=${taskId}`, {
      method: "DELETE"
    }).then((res) => {
      setDeleteLoader(false);
      if (res) {
        window.location.replace("/profile/calendar");
      }
    });
  }

  function nextDay() {
    getReportFromDate(getCreatedDate(nextReportDay));
    previousReportDay.setDate(previousReportDay.getDate() + 2);
  }

  function previousDay() {
    getReportFromDate(getCreatedDate(previousReportDay));
    nextReportDay.setDate(nextReportDay.getDate() - 2);
  }

  useEffect(() => {
    getReportFromDate(params.date);
  }, []);

  return (
    <div className="viewReport">
      <ProfileHeader />
      <Navigation />
      <div className="container">
        <div className="viewReport__info">
          {localStorage.getItem("role_status") !== "18" && (
            <>
              <ProfileBreadcrumbs
                links={[
                  { name: "Главная", link: "/profile" },
                  { name: "Ваша отчетность", link: "/profile/calendar" },
                  { name: "Просмотр отчета за день", link: "/profile/view" }
                ]}
              />
              <h2 className="viewReport__title">
                Ваши отчеты - <span>просмотр отчета за день</span>
              </h2>
            </>
          )}
          <Link
            className="viewReport__back"
            to={
              localStorage.getItem("role_status") === "18"
                ? `/profile/employees/report/${params.id}`
                : `/profile/calendar`
            }
          >
            <img src={arrow} alt="#" />
            <p>Вернуться</p>
          </Link>
          {localStorage.getItem("role_status") !== "18" && (
            <div className="viewReport__bar">
              <button className="viewReport__bar__edit">Редактировать</button>
              {deleteLoader ? (
                <Loader style={"green"} />
              ) : (
                <button
                  onClick={deleteReport}
                  className={
                    taskText.length
                      ? "viewReport__bar__delete"
                      : "viewReport__bar__delete disable"
                  }
                >
                  Удалить отчет
                </button>
              )}
            </div>
          )}
        </div>
        <div className="viewReport__switch-date">
          <div onClick={() => previousDay()}>
            <Link
              to={`/profile/calendar/view/${getCreatedDate(
                previousReportDay
              )}/${params.id}`}
            >
              <div className="viewReport__switch-date__prev switch-date">
                <img src={arrowSwitchDate} alt="arrow" />
              </div>
            </Link>
          </div>

          <p>{getCorrectDate(params.date)}</p>

          <div
            onClick={() => nextDay()}
            className={`${
              getCreatedDate(currentDay) === params.date ? "disable" : ""
            }`}
          >
            <Link
              to={`/profile/calendar/view/${getCreatedDate(nextReportDay)}/${
                params.id
              }`}
            >
              <div className={`viewReport__switch-date__next switch-date`}>
                <img src={arrowSwitchDate} alt="arrow" />
              </div>
            </Link>
          </div>
        </div>
        {loader && <Loader width={75} height={75} />}
        {Boolean(taskText.length) && (
          <div className="viewReport__content">
            <div className="table__container">
              <table className="viewReport__done">
                <thead>
                  <tr>
                    <th>
                      <p>Какие задачи выполнены?</p>
                    </th>
                    <th>
                      <p>Время</p>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {taskText.length &&
                    taskText.map((task, index) => {
                      return (
                        <tr key={task.id}>
                          <td>
                            <p>
                              {index + 1}. {task.task}
                            </p>
                          </td>
                          <td>
                            <div className="viewReport__done__hours__item">
                              <span>{Math.floor(task.hours)}</span>
                              <p className="hours">
                                {hourOfNum(Math.floor(task.hours))}
                              </p>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  <tr>
                    <td></td>
                    <td>
                      <span>
                        Всего: {totalHours} {hourOfNum(totalHours)}
                      </span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            {Boolean(difficulties.length) && (
              <div className="viewReport__item">
                <h3>Какие сложности возникли?</h3>
                {difficulties.map((item, index) => {
                  return <p key={index}>{item}</p>;
                })}
              </div>
            )}
            {Boolean(tomorrowTask.length) && (
              <div className="viewReport__item">
                <h3>Что планируется сделать завтра?</h3>
                {tomorrowTask.map((item, index) => {
                  return <p key={index}>{item}</p>;
                })}
              </div>
            )}
          </div>
        )}
        {!Boolean(taskText.length) && !loader && (
          <div className="viewReport__noTask">
            {localStorage.getItem("role_status") === "4" ? (
              <p>
                В этот день вы <span>не заполняли</span> отчет
              </p>
            ) : (
              <p>Отчет за день не заполнен</p>
            )}
          </div>
        )}
        <Footer />
      </div>
    </div>
  );
};
