import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Link, useNavigate } from "react-router-dom";

import { deleteProject, modalToggle } from "@redux/projectsTrackerSlice";

import { copyProjectLink, urlForLocal } from "@utils/helper";

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

import { useNotification } from "@hooks/useNotification";

import AcceptModal from "@components/Modal/AcceptModal/AcceptModal";
import { ModalSelect } from "@components/Modal/ModalSelect/ModalSelect";
import TrackerModal from "@components/Modal/Tracker/TrackerModal/TrackerModal";

import archiveSet from "assets/icons/archive.svg";
import del from "assets/icons/delete.svg";
import edit from "assets/icons/edit.svg";
import link from "assets/icons/link.svg";

import "./projectTicket.scss";

export const ProjectTicket = ({ project, index }) => {
  const [modalSelect, setModalSelect] = useState(false);
  const [modalAdd, setModalAdd] = useState(false);
  const [modalDelete, setModalDelete] = useState(false);
  const [acceptModalOpen, setAcceptModalOpen] = useState(false);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { showNotification } = useNotification();

  useEffect(() => {
    initListeners();
  }, []);

  function initListeners() {
    document.addEventListener("click", closeByClickingOut);
  }

  function closeByClickingOut(event) {
    const path = event.path || (event.composedPath && event.composedPath());

    if (
      event &&
      !path.find(
        (div) =>
          div.classList && div.classList.contains(`project-${project.id}`)
      )
    ) {
      setModalSelect(false);
    }
  }

  function removeProject() {
    apiRequest("/project/update", {
      method: "PUT",
      data: {
        project_id: project.id,
        status: 10
      }
    }).then(() => {
      dispatch(deleteProject(project));
      showNotification({
        show: true,
        text: "Проект успешно был перемещен в архив",
        type: "archive"
      });
    });
  }
  // showNotification({
  //   show: true,
  //   text: "Проект успешно удален",
  //   type: "success"
  // });

  function closeAcceptModal() {
    setAcceptModalOpen(false);
    setModalDelete(false);
  }

  return (
    <div className={`project project-${project.id}`} key={index}>
      <Link
        to={`/tracker/project/${project.id}`}
        className="project__open-tracker"
      >
        <div className="project__link">{project.name}</div>

        <div className="project__info">
          {/* <p>Открытые задачи</p>
          <span className="count">
            {project.columns.reduce(
              (accumulator, currentValue) =>
                accumulator + currentValue.tasks.length,
              0
            )}
          </span> */}
          <img
            src={urlForLocal(project.owner_info.avatar)}
            alt="avatar"
            className="project__avatar"
          />
          <div>
            <p>Создатель проекта</p>
            <span>{project.owner_info.fio}</span>
          </div>
        </div>
      </Link>

      {/* <Link
        to={`/profile/statistics/${project.id}`}
        className="project__statistics"
      >
        Посмотреть статистику
      </Link> */}

      <span className="project-stats" onClick={() => {}}>
        Просмотреть <br />
        статистику проекта
      </span>

      <span
        className="menu-settings"
        onClick={() => {
          setModalSelect(!modalSelect);
        }}
      >
        ...
      </span>

      <TrackerModal
        active={modalAdd}
        setActive={setModalAdd}
        defautlInput={project.name}
        projectId={project.id}
      ></TrackerModal>

      <ModalSelect active={modalSelect} onClick={(e) => e.stopPropagation()}>
        <div className="project__settings-menu">
          <div
            onClick={() => {
              dispatch(modalToggle("edit-project"));
              setModalAdd(true);
              setModalSelect(false);
            }}
          >
            <img src={edit}></img>
            <p>редактировать</p>
          </div>
          <div
            onClick={() => {
              copyProjectLink(project.id);
              showNotification({
                show: true,
                text: "Ссылка скопирована в буфер обмена",
                type: "copy"
              });
            }}
          >
            <img src={link}></img>
            <p>скопировать ссылку</p>
          </div>
          <div
            onClick={() => {
              setModalSelect(false);
              setAcceptModalOpen(true);
            }}
          >
            {/* <img src={archiveSet}></img>
            <p>в архив</p>
          </div>
          <div
            onClick={() => {
              navigate(`/profile/statistics/${project.id}`);
            }}
          > */}
            <img src={archiveSet}></img>
            <p>статистика</p>
          </div>
          <div
            onClick={() => {
              setModalDelete(true);
              setModalSelect(false);
            }}
          >
            <img src={del}></img>
            <p>удалить</p>
          </div>
        </div>
      </ModalSelect>
      {acceptModalOpen && (
        <AcceptModal
          title={"Вы действительно хотите переместить проект в архив?"}
          closeModal={closeAcceptModal}
          agreeHandler={removeProject}
        />
      )}

      {modalDelete && (
        <AcceptModal
          title={"Вы действительно хотите удалить проект?"}
          closeModal={closeAcceptModal}
          agreeHandler={removeProject}
        />
      )}
    </div>
  );
};

export default ProjectTicket;
