import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";

import { getProfileInfo } from "@redux/outstaffingSlice";

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

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

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

import { Footer } from "@components/Common/Footer/Footer";
import { Navigation } from "@components/Navigation/Navigation";
import { ProfileBreadcrumbs } from "@components/ProfileBreadcrumbs/ProfileBreadcrumbs";
import { ProfileHeader } from "@components/ProfileHeader/ProfileHeader";

import rightArrow from "assets/icons/arrows/arrowRight.svg";
import arrow from "assets/icons/arrows/left-arrow.png";
import arrowDown from "assets/icons/arrows/selectArrow.png";
import deleteIcon from "assets/icons/closeProjectPersons.svg";
import gitImgItem from "assets/icons/gitItemImg.svg";
import avatarMok from "assets/images/avatarMok.png";

import "./summary.scss";

export const Summary = () => {
  if (localStorage.getItem("role_status") === "18") {
    return <Navigate to="/profile" replace />;
  }
  const profileInfo = useSelector(getProfileInfo);
  const [openGit, setOpenGit] = useState(false);
  const [gitInfo, setGitInfo] = useState([]);
  const [editSummeryOpen, setEditSummeryOpen] = useState(false);
  const [editSkills, setEditSkills] = useState(false);
  const [summery, setSummery] = useState("");
  const [selectedSkills, setSelectedSkills] = useState([]);
  const [selectSkillsOpen, setSelectSkillsOpen] = useState(false);
  const [skillsList, seSkillsList] = useState([]);
  const { showNotification } = useNotification();

  useEffect(() => {
    apiRequest(
      `/profile/portfolio-projects?card_id=${localStorage.getItem("cardId")}`
    ).then((responseGit) => setGitInfo(responseGit));
  }, []);

  useEffect(() => {
    setSummery(profileInfo.vc_text);
    setSelectedSkills(profileInfo.skillValues);
  }, [profileInfo]);

  useEffect(() => {
    apiRequest(`/skills/get-skills-list`).then((el) => {
      seSkillsList(el);
    });
  }, []);

  function setSkills() {
    apiRequest("/resume/edit-skills", {
      method: "PUT",
      data: {
        UserCard: {
          skill: selectedSkills.map((item) => item.skill_id)
        }
      }
    }).then(() => {});
  }

  function editSummery() {
    apiRequest("/resume/edit-text", {
      method: "PUT",
      data: {
        resume: summery
      }
    }).then(() => {
      showNotification({
        show: true,
        text: "Изменения успешно сохранены",
        type: "success"
      });
    });
  }
  return (
    <div className="summary">
      <ProfileHeader />
      <Navigation />
      <div className="container">
        <div className="summary__content">
          <ProfileBreadcrumbs
            links={[
              { name: "Главная", link: "/profile" },
              { name: "Резюме", link: "/profile/summary" }
            ]}
          />
          <h2 className="summary__title">
            Ваше резюме {openGit && <span>- Git</span>}
          </h2>
          {openGit && (
            <div className="summary__back" onClick={() => setOpenGit(false)}>
              <img src={arrow} alt="arrow" />
              <p>Вернуться</p>
            </div>
          )}
          <div className={openGit ? "summary__info open-git" : "summary__info"}>
            <div className="summary__person">
              <img
                src={
                  profileInfo?.photo
                    ? urlForLocal(profileInfo.photo)
                    : avatarMok
                }
                className="summary__avatar"
                alt="avatar"
              />
              <p className="summary__name">
                {profileInfo?.fio || profileInfo?.username}{" "}
                {profileInfo.specification}
              </p>
              <hr />
              <div className="summary__direction">Front End</div>
              <div className="summary__level">Middle+</div>
            </div>
            {!openGit && (
              <button className="summary__git" onClick={() => setOpenGit(true)}>
                Git
              </button>
            )}
          </div>
        </div>
        {!openGit && (
          <div className="summary__skills skills__section">
            <div className="summary__sections__head">
              <h3>Основной стек</h3>
              <button
                className={editSkills ? "edit" : ""}
                onClick={() => {
                  if (editSkills) {
                    setSkills();
                  }
                  setEditSkills(!editSkills);
                }}
              >
                {editSkills ? "Сохранить" : "Редактировать"}
              </button>
            </div>
            <div className="skills__section__items">
              {editSkills ? (
                <div className="edit-skills">
                  {selectedSkills &&
                    selectedSkills.map((skill) => {
                      return (
                        <span key={skill.skill_id}>
                          {skill.skill.name}
                          <img
                            src={deleteIcon}
                            alt="deleteIcon"
                            onClick={() =>
                              setSelectedSkills((prevValue) =>
                                prevValue.filter(
                                  (item) => item.skill_id !== skill.skill_id
                                )
                              )
                            }
                          />
                        </span>
                      );
                    })}
                  <div className="select-skills">
                    <div
                      className="select-skills__name"
                      onClick={() => setSelectSkillsOpen(!selectSkillsOpen)}
                    >
                      Выберите скилл
                      <img
                        className={selectSkillsOpen ? "open" : ""}
                        src={arrowDown}
                      />
                    </div>
                    {selectSkillsOpen && (
                      <div className="select-skills__dropDown">
                        {skillsList.map((skill) => {
                          return (
                            <p
                              onClick={() =>
                                setSelectedSkills((prevValue) => [
                                  ...prevValue,
                                  { skill: skill, skill_id: skill.id }
                                ])
                              }
                              key={skill.id}
                              className="select-skills__item"
                            >
                              {skill.name}
                            </p>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="skills__section__items__wrapper">
                  {selectedSkills &&
                    selectedSkills.map((skill, index) => (
                      <span key={skill.id} className="skill_item">
                        {skill.skill.name}
                        {selectedSkills.length > index + 1 && ","}
                      </span>
                    ))}
                </div>
              )}
            </div>
          </div>
        )}
        {profileInfo.vc_text && !openGit && (
          <div className="summary__experience">
            <div className="experience__block">
              <div className="summary__sections__head">
                <h3>Опыт работы</h3>
                <button
                  className={editSummeryOpen ? "edit" : ""}
                  onClick={() => {
                    if (editSummeryOpen) {
                      editSummery();
                    }
                    setEditSummeryOpen(!editSummeryOpen);
                  }}
                >
                  {editSummeryOpen ? "Сохранить" : "Редактировать"}
                </button>
              </div>
              {editSummeryOpen ? (
                <CKEditor
                  editor={ClassicEditor}
                  data={summery}
                  config={{
                    removePlugins: [
                      "CKFinderUploadAdapter",
                      "CKFinder",
                      "EasyImage",
                      "Image",
                      "ImageCaption",
                      "ImageStyle",
                      "ImageToolbar",
                      "ImageUpload",
                      "MediaEmbed",
                      "BlockQuote"
                    ]
                  }}
                  onChange={(event, editor) => {
                    const data = editor.getData();
                    setSummery(data);
                  }}
                />
              ) : (
                <div
                  className="experience__content"
                  dangerouslySetInnerHTML={{ __html: summery }}
                ></div>
              )}
            </div>
          </div>
        )}
        {openGit && (
          <div className="summary__section-git">
            <div className="summary__sections__head">
              <h3>Ваши репозитории</h3>
              <button>Редактировать</button>
            </div>
            <div className="summary__section-git-items">
              {Boolean(gitInfo.length) &&
                gitInfo.map((itemGit) => {
                  return (
                    <a
                      href={itemGit.link}
                      target="_blank"
                      rel="noreferrer"
                      key={itemGit.id}
                      className="summary__section-git-item git-item"
                    >
                      <div className="git-item__info">
                        <div className="git-item__info__about">
                          <img src={gitImgItem} alt="gitImg" />
                          <div className="git-item__info__name">
                            <h4>{itemGit.title}</h4>
                            <p>{itemGit.description}</p>
                          </div>
                        </div>
                        <div className="git-item__info__specification">
                          <span className="git-item__lineSkill" />
                          <p>{itemGit.main_stack}</p>
                        </div>
                      </div>
                      <a
                        className="git-item__link"
                        href={itemGit.link}
                        target="_blank"
                        rel="noreferrer"
                      >
                        <img src={rightArrow} alt="arrowRight" />
                      </a>
                    </a>
                  );
                })}
              {!Boolean(gitInfo.length) && (
                <p className="no-git-items">Нет актуальных проектов</p>
              )}
            </div>
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
};
