import IconButton from "../../components/IconButton/IconButton";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  fetchAdsCandidates,
  filterCandidates,
} from "../../store/actions/candidates/candidatesActions";
import tableImage from "../../assets/images/table.png";
import adImage from "../../assets/images/.net_icon.png";
import filterImage from "../../assets/images/filters.png";
import { formatDate } from "../../util/helpers/dateHelpers";
import planeImage from "../../assets/images/planeVector.png";
import arrow_left from "../../assets/images/arrow_left.png";
import arrow_right from "../../assets/images/arrow_right.png";
import { useMediaQuery } from "@mui/material";
import { useTheme } from "@mui/system";
import { CANDIDATES_PAGE } from "../../constants/pages";
import PropTypes from "prop-types";
import Slider from "react-slick";
import CandidateCard from "../../components/Candidates/CandidateCard";
import useDynamicRefs from "use-dynamic-refs";
import CandidateFilters from "../../components/Candidates/CandidateFilters";
import Pagination from "@mui/material/Pagination";
import { PAGE_SIZE_CANDIDATES } from "../../constants/keyCodeConstants";

const CandidatesPage = ({ history }) => {
  const dispatch = useDispatch();
  const { candidates } = useSelector((s) => s.candidates);
  const { pagination } = useSelector((s) => s.candidates); // pagination is total number of candidates on backend
  const { adsCandidates } = useSelector((s) => s.candidates);
  const theme = useTheme();
  const matches = useMediaQuery(theme.breakpoints.down("sm"));
  const [isTableView, setIsTableView] = useState(true);
  const [getRef, setRef] = useDynamicRefs();
  const [toggleFiltersDrawer, setToggleFiltersDrawer] = useState(false);
  const [page, setPage] = React.useState(1);

  useEffect(() => {
    dispatch(
      filterCandidates({
        currentPage: page,
        pageSize: PAGE_SIZE_CANDIDATES,
        minExperience: 0,
        maxExperience: 0,
        employmentType: "",
        minDateOfApplication: "",
        maxDateOfApplication: "",
        technologies: [],
      })
    );
    dispatch(fetchAdsCandidates());
  }, [dispatch]);

  const navigate = (applicantId) => {
    history.push({
      pathname: CANDIDATES_PAGE + "/" + applicantId,
      state: {
        from: history.location.pathname,
      },
    });
  };

  const changeView = () => {
    setIsTableView(!isTableView);
  };

  const handleToggleFiltersDrawer = () => {
    setToggleFiltersDrawer((oldState) => !oldState);
  };

  var settings = {
    dots: false,
    infinite: false,
    speed: 400,
    slidesToShow: 4,
    slidesToScroll: 4,
    initialSlide: 0,
    arrows: true,
    variableWidth: true,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 3,
          infinite: true,
          dots: false,
        },
      },
      {
        breakpoint: 900,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2,
          initialSlide: 0,
        },
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
        },
      },
    ],
  };

  const getDummyCandidates = (len) => {
    const candidates = [];

    for (let i = 0; i < 4 - len + 1; i++) {
      candidates.push(
        <CandidateCard key={i} className="hiddenAd" history={history} />
      );
    }

    return candidates;
  };

  const activeAdsArrowLeftHandler = (index) => {
    getRef(index.toString()).current.slickPrev();
  };

  const activeAdsArrowRightHandler = (index) => {
    getRef(index.toString()).current.slickNext();
  };

  const handleChange = (event, value) => {
    dispatch(
      filterCandidates({
        currentPage: value,
        pageSize: PAGE_SIZE_CANDIDATES,
        minExperience: 0,
        maxExperience: 5,
        employmentType: "Intership",
        minDateOfApplication: "10/05/2020",
        maxDateOfApplication: "10/10/2022",
        technologies: [],
      })
    );
    setPage(value);
  };

  return (
    <div className="main-candidates-container pl-144 pt-36px">
      <CandidateFilters
        open={toggleFiltersDrawer}
        handleClose={handleToggleFiltersDrawer}
        pageSize={PAGE_SIZE_CANDIDATES}
        currentPage={page}
      />
      <div className="l-t-rectangle"></div>
      <div className="r-b-rectangle"></div>
      <div className="top-candidates-container">
        {!matches ? (
          <p className="candidates-header">Kandidati</p>
        ) : (
          <p className="candidates-header" style={{ fontSize: "12px" }}>
            Kandidati
          </p>
        )}
        <div className="candidates-options-container">
          {!matches ? (
            isTableView ? (
              <IconButton
                className="c-btn c-btn--primary-outlined candidate-btn all-white-btn"
                onClick={changeView}
              >
                Tablicni prikaz
                <img
                  src={tableImage}
                  alt="table"
                  className="candidates-image"
                />
              </IconButton>
            ) : (
              <IconButton
                className="c-btn c-btn--primary-outlined candidate-btn"
                onClick={changeView}
              >
                Tablicni prikaz
                <img
                  src={tableImage}
                  alt="table"
                  className="candidates-image"
                />
              </IconButton>
            )
          ) : (
            <IconButton className="c-btn--primary-outlined c-btn candidate-btn-mobile">
              <img
                className="candidate-image-mobile"
                src={tableImage}
                alt="table"
              />
            </IconButton>
          )}
          {!matches ? (
            <IconButton
              className="c-btn c-btn--primary-outlined candidate-btn"
              onClick={handleToggleFiltersDrawer}
            >
              Filteri
              <img
                src={filterImage}
                alt="filter"
                className="candidates-image"
              />
            </IconButton>
          ) : (
            <IconButton
              className="c-btn c-btn--primary-outlined candidate-btn-mobile"
              onClick={handleToggleFiltersDrawer}
            >
              <img
                src={filterImage}
                alt="filter"
                className="candidate-image-mobile"
              />
            </IconButton>
          )}
        </div>
      </div>
      {isTableView ? (
        <div className="candidates-table">
          <table
            className="usersTable"
            style={{ width: "1117px", height: "100px" }}
          >
            <thead>
              <tr className="headingRow">
                <th>Ime i prezime</th>
                <th>Iskustvo</th>
                <th>Datum prijave</th>
                <th>Pozicija</th>
                <th>CV link</th>
              </tr>
            </thead>
            <tbody>
              {candidates.map((candidate, index) => (
                <tr
                  key={index}
                  className="secondaryRow cadidate-row"
                  style={{
                    width: "800px",
                    height: "40px",
                    borderRadius: "12px",
                    cursor: "pointer",
                  }}
                  onClick={() => navigate(candidate.applicantId)}
                >
                  <td>
                    {candidate.firstName} {candidate.lastName}
                  </td>
                  <td>{candidate.experience}</td>
                  <td>{formatDate(candidate.dateOfApplication)}</td>
                  <td>{candidate.position}</td>
                  <td>
                    <a href={candidate.CV} className="cvLink">
                      {candidate.firstName}
                      {candidate.lastName}.pdf
                    </a>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <Pagination
            count={
              parseInt(pagination) <= PAGE_SIZE_CANDIDATES
                ? 1
                : Math.ceil(parseInt(pagination) / PAGE_SIZE_CANDIDATES)
            }
            color="primary"
            style={{ alignSelf: "center", marginTop: "20px" }}
            onChange={handleChange}
            shape="rounded"
          />
        </div>
      ) : (
        <div className="ads-candidates-container top-cnd">
          {adsCandidates.map((adCandidates, index) => (
            <div className="ads-candidates" key={index}>
              <div className="ads-candidates-top-container">
                <img src={adImage} style={{ width: "49px", height: "39px" }} />
                <p className="ads-candidates-title">{adCandidates.title}</p>
                <p className="ads-candidates-numberOfApplicants">
                  | {adCandidates.nubmerOfApplicants} prijavljenih
                </p>
              </div>
              <div
                className="ads-candidates-slider"
                style={{ display: "flex", marginTop: "31px" }}
              >
                {adCandidates.applicants.length > 3 && (
                  <div className="active-ads-ads-arrows">
                    <button onClick={() => activeAdsArrowLeftHandler(index)}>
                      <img src={arrow_left} alt="arrow-left" />
                    </button>
                    <button onClick={() => activeAdsArrowRightHandler(index)}>
                      <img src={arrow_right} alt="arrow-right" />
                    </button>
                  </div>
                )}
                <Slider
                  {...settings}
                  ref={setRef(index.toString())}
                  style={{ width: "100%" }}
                >
                  {adCandidates.applicants.map((candidate, index) => (
                    <CandidateCard
                      key={index}
                      candidate={candidate}
                      history={history}
                      className={index === 0 ? "" : "left-move-candidateAd"}
                    />
                  ))}
                  {adCandidates.applicants.length <= 4 &&
                    getDummyCandidates(adCandidates.applicants.length)}
                </Slider>
              </div>
            </div>
          ))}
        </div>
      )}
      <IconButton className={'c-btn  candidate-btn invite-btn invite-btn-color ' + (isTableView === false ? 'proba' : '')}>
        <img src={planeImage} alt="table" className="candidates-image" />
        Invite
      </IconButton>
    </div>
  );
};

CandidatesPage.propTypes = {
  history: PropTypes.shape({
    replace: PropTypes.func,
    push: PropTypes.func,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }),
  }),
};

export default CandidatesPage;
