import { getTheme } from "@table-library/react-table-library/baseline";
import { CompactTable } from "@table-library/react-table-library/compact";
import { usePagination } from "@table-library/react-table-library/pagination";
import { useSort } from "@table-library/react-table-library/sort";
import { useTheme } from "@table-library/react-table-library/theme";
import React, { useEffect, useState } from "react";
import { Link, Navigate } from "react-router-dom";

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

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

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 rightArrow from "assets/icons/arrows/arrowRight.svg";
import folder from "assets/icons/folder.svg";
import report from "assets/icons/report.svg";

import "./partnerСategories.scss";

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

  const [loader, setLoader] = useState(false);
  const theme = useTheme(getTheme());
  const [nodes, setNodes] = useState([]);
  const [initialNodes, setInitialNodes] = useState([]);
  const [activeTab, setActiveTab] = useState(0);

  const [search, setSearch] = useState("");

  const tabs = [
    {
      name: "Фронтенд",
      value: 2
    },
    {
      name: "Бэкенд",
      value: 1
    }
  ];

  const COLUMNS = [
    {
      label: "",
      renderCell: (item) => (
        <Link to={`/profile/summary/${item.user_id}`}>
          <img
            className="table__avatar"
            src={urlForLocal(item?.employee.avatar)}
            alt="avatar"
          />
        </Link>
      )
    },
    {
      label: "Данные",
      renderCell: (item) => (
        <Link className="table__info" to={`/profile/summary/${item.user_id}`}>
          <p>{item?.employee.fio}</p>
          <span>
            {item?.employee.level_title} / {item?.employee.position.name}
          </span>
        </Link>
      )
    },
    {
      label: "Участвует  в проекте",
      renderCell: (item) => (
        <div className="table__project">
          {item?.employee.projects.length ? (
            item.employee.projects.map((project) => {
              return (
                <div className="table__project__item" key={project.id}>
                  <img src={folder} alt="folder" />{" "}
                  <p>{project.project.name}</p>
                </div>
              );
            })
          ) : (
            <span>Нет проектов</span>
          )}
        </div>
      )
    },
    {
      label: "Отчетность",
      renderCell: (item) => (
        <Link
          className="table__link"
          to={`/profile/employees/report/${item.user_id}`}
        >
          <img src={report} alt="report" />
          Подробный отчет
          <div className="img__wrapper">
            <img src={rightArrow} alt="arrow" />
          </div>
        </Link>
      )
    },
    {
      label: <span className="table__action">Действие</span>,
      renderCell: () => <div className="table__more"></div>
    }
  ];

  let data = { nodes };

  const sort = useSort(
    data,
    {
      onChange: onSortChange
    },
    {
      sortFns: {
        NAME: (array) =>
          array.sort((a, b) => a.employee.fio.localeCompare(b.employee.fio))
      }
    }
  );

  const pagination = usePagination(data, {
    state: {
      page: 0,
      size: 10
    }
  });

  useEffect(() => {
    setLoader(true);
    apiRequest("/project/my-employee").then((el) => {
      setNodes(el.managerEmployees);
      setInitialNodes(el.managerEmployees);
      setLoader(false);
    });
  }, []);

  const handleSearch = (event) => {
    setSearch(event.target.value);
    setNodes(
      initialNodes.filter((item) =>
        item.employee.fio
          .toLowerCase()
          .includes(event.target.value.toLowerCase())
      )
    );
  };

  function onSortChange(action, state) {
    console.log(action, state);
  }

  return (
    <div className="partner-categories">
      <ProfileHeader />
      <Navigation />
      <div className="container">
        <ProfileBreadcrumbs
          links={[
            { name: "Главная", link: "/profile" },
            { name: "Данные моего персонала", link: "/profile/employees" }
          ]}
        />
        <h2 className="partner-categories__title">Данные персонала</h2>
        {loader ? (
          <Loader style={"green"} height={80} width={80} />
        ) : (
          <div className="partner-categories__items">
            {Boolean(initialNodes.length) ? (
              <>
                <label className="table__search" htmlFor="search">
                  Поиск по имени:
                  <input
                    id="search"
                    type="text"
                    value={search}
                    placeholder="Поиск по сотрудникам"
                    onChange={handleSearch}
                  />
                </label>
                <div className="table__tabs">
                  <div
                    onClick={() => {
                      setActiveTab(0);
                      setNodes(initialNodes);
                    }}
                    className={
                      activeTab === 0
                        ? "table__tab table__tab--active"
                        : "table__tab"
                    }
                  >
                    Все
                  </div>
                  {tabs.map((tab) => {
                    return (
                      <div
                        onClick={() => {
                          setActiveTab(tab.name);
                          setNodes(
                            initialNodes.filter(
                              (item) => item.employee.position.id === tab.value
                            )
                          );
                        }}
                        className={
                          activeTab === tab.name
                            ? "table__tab table__tab--active"
                            : "table__tab"
                        }
                        key={tab.value}
                      >
                        {tab.name}
                      </div>
                    );
                  })}
                </div>
                <CompactTable
                  columns={COLUMNS}
                  data={data}
                  theme={theme}
                  sort={sort}
                  pagination={pagination}
                />
                {Boolean(nodes.length) &&
                  pagination.state.getPages(data.nodes).length > 1 && (
                    <div className="table__pagination">
                      <button
                        className={
                          pagination.state.page === 0
                            ? "switch disable"
                            : "switch"
                        }
                        type="button"
                        disabled={pagination.state.page === 0}
                        onClick={() =>
                          pagination.fns.onSetPage(pagination.state.page - 1)
                        }
                      >
                        {"<"}
                      </button>
                      <span className="table__pages">
                        {pagination.state
                          .getPages(data.nodes)
                          .map((_, index) => (
                            <button
                              key={index}
                              type="button"
                              className={
                                pagination.state.page === index
                                  ? "page page--active "
                                  : "page"
                              }
                              onClick={() => pagination.fns.onSetPage(index)}
                            >
                              {index + 1}
                            </button>
                          ))}
                      </span>
                      <button
                        className={
                          pagination.state.page + 1 ===
                          pagination.state.getPages(data.nodes).length
                            ? "switch disable"
                            : "switch"
                        }
                        type="button"
                        disabled={
                          pagination.state.page + 1 ===
                          pagination.state.getPages(data.nodes).length
                        }
                        onClick={() =>
                          pagination.fns.onSetPage(pagination.state.page + 1)
                        }
                      >
                        {">"}
                      </button>
                    </div>
                  )}
              </>
            ) : (
              <div className="partner-categories__empty">
                У вас нет нанятого персонала, разместите вашу <br /> первую
                вакансию на вкладке{" "}
                <Link to={`/profile/requests`}>
                  <b>Мои вакансии</b>
                </Link>
              </div>
            )}
          </div>
        )}
      </div>
      <Footer />
    </div>
  );
};
