import React, { forwardRef, useEffect, useState } from "react";
import { useDispatch } from "react-redux";

import { movePositionProjectTask } from "@redux/projectsTrackerSlice";

import { getCorrectDate } from "@utils/calendarHelper";
import { removeLast, urlForLocal } from "@utils/helper";

import TrackerSelectColumn from "@components/TrackerSelectColumn/TrackerSelectColumn";

import commentsBoard from "assets/icons/commentsBoard.svg";
import filesBoard from "assets/icons/filesBoard.svg";
import avatarMok from "assets/images/avatarMok.webp";

import "./trackerCardTask.scss";

const TrackerCardTask = forwardRef(
  (
    {
      task,
      projectBoard,
      titleColor,
      column,
      openTicket,
      startWrapperIndexTest,
      setWrapperHover
    },
    ref
  ) => {
    const dispatch = useDispatch();
    const [taskHover, setTaskHover] = useState({});

    const priority = {
      2: "Высокий",
      1: "Средний",
      0: "Низкий"
    };

    const priorityClass = {
      2: "high",
      1: "middle",
      0: "low"
    };

    function dragDropTaskHandler(e, task, column) {
      e.preventDefault();
      if (task.id === startWrapperIndexTest.current.task.id) {
        return;
      }

      const finishTask = column.tasks.indexOf(task);

      dispatch(
        movePositionProjectTask({
          startTask: startWrapperIndexTest.current.task,
          finishTask: task,
          finishIndex: finishTask
        })
      );
    }

    function dragOverTaskHandler(e, task) {
      e.preventDefault();
      if (startWrapperIndexTest.current.task.id === task.id) {
        return;
      }
      setTaskHover((prevState) => ({ [prevState]: false, [task.id]: true }));
    }

    function dragStartHandler(e, task, columnId) {
      startWrapperIndexTest.current = { task: task, index: columnId };
    }

    function dragLeaveTaskHandler() {
      setTaskHover((prevState) => ({ [prevState]: false }));
    }

    function dragEndTaskHandler() {
      setTaskHover((prevState) => ({ [prevState]: false }));
      setWrapperHover((prevState) => ({
        [prevState]: false
      }));
    }

    useEffect(() => {
      const tasksHover = {};
      const columnHover = {};

      if (Object.keys(projectBoard).length) {
        projectBoard.columns.forEach((column) => {
          columnHover[column.id] = false;
          column.tasks.forEach((task) => (tasksHover[task.id] = false));
        });
      }
      setWrapperHover(columnHover);
      setTaskHover(tasksHover);
    }, [projectBoard]);

    return (
      <>
        <div
          ref={ref}
          key={task.id}
          className={`tasks__board__item ${
            taskHover[task.id] ? "task__hover" : ""
          }`}
          draggable={true}
          onDragStart={(e) => dragStartHandler(e, task, column.id)}
          onDragOver={(e) => dragOverTaskHandler(e, task)}
          onDragLeave={(e) => dragLeaveTaskHandler(e)}
          onDragEnd={() => dragEndTaskHandler()}
          onDrop={(e) => dragDropTaskHandler(e, task, column)}
          onClick={() => openTicket(task)}
        >
          <div className="tasks__board__item__title">
            <p className="task__board__item__title">{task.title}</p>
          </div>
          <p
            dangerouslySetInnerHTML={{
              __html: task.description
            }}
            className="tasks__board__item__description"
          ></p>
          {Boolean(task.mark.length) && (
            <div className="tasks__board__item__tags">
              {task.mark.map((tag) => {
                return (
                  <div
                    className="tag-item"
                    key={tag.id}
                    style={{ background: tag.color }}
                  >
                    <p>{tag.slug}</p>
                  </div>
                );
              })}
            </div>
          )}
          <div className="tasks__board__item__container">
            {typeof task.execution_priority === "number" && (
              <div className="tasks__board__item__priority">
                <p>⚡</p>
                <span className={priorityClass[task.execution_priority]}>
                  {priority[task.execution_priority]}
                </span>
              </div>
            )}
            {task.dead_line && (
              <div className="tasks__board__item__dead-line">
                <p>⌛</p>
                <span style={{ color: titleColor }}>
                  {getCorrectDate(task.dead_line)}
                </span>
              </div>
            )}
          </div>

          <div className="tasks__board__item__info">
            <div className="tasks__board__item__executor">
              <img
                src={
                  task.executor?.avatar
                    ? urlForLocal(task.executor?.avatar)
                    : avatarMok
                }
                alt="avatar"
              />
              <span>
                {removeLast(task.executor?.fio) || "Исполнитель не назначен"}
              </span>
            </div>
            <div className="tasks__board__item__info__tags">
              <div className="tasks__board__item__info__more">
                <img src={commentsBoard} alt="commentsImg" />
                <span>{task.comment_count}</span>
              </div>
              <div className="tasks__board__item__info__more">
                <img src={filesBoard} alt="filesImg" />
                <span>{task.file_count}</span>
              </div>
            </div>
          </div>
        </div>
        <TrackerSelectColumn
          columns={projectBoard.columns.filter((item) => item.id !== column.id)}
          currentColumn={column}
          task={task}
        />
      </>
    );
  }
);

TrackerCardTask.displayName = "TrackerCardTask";

export default TrackerCardTask;
