import React, { useEffect } from "react";
import Pagination from "@mui/material/Pagination";
import { formatDate } from "../../util/helpers/dateHelpers";
import { useDispatch, useSelector } from "react-redux";
import PropTypes from "prop-types";
import { CANDIDATES_PAGE } from "../../constants/pages";
import { filterCandidates } from "../../store/actions/candidates/candidatesActions";
import { PAGE_SIZE_CANDIDATES } from "../../constants/keyCodeConstants";
import { useTheme } from "@mui/system";
import { useMediaQuery } from "@mui/material";

const TableViewPage = ({ history, setPage, page, search }) => {
  const dispatch = useDispatch();
  const { candidates } = useSelector((s) => s.candidates);
  const { pagination } = useSelector((s) => s.candidates); // pagination is total number of candidates on backend
  const theme = useTheme();
  const matches = useMediaQuery(theme.breakpoints.down("361"));

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

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

  const handleChange = (_, value) => {
    dispatch(
      filterCandidates({
        currentPage: value,
        pageSize: PAGE_SIZE_CANDIDATES,
        minExperience: 0,
        maxExperience: 0,
        employmentType: "",
        minDateOfApplication: "",
        maxDateOfApplication: "",
        technologies: [],
      })
    );
    setPage(value);
  };

  const formatLabel = (string, value) => {
    if (!value) {
      return string;
    }
    return (
      <span>
        {string.split(value).reduce((prev, current, i) => {
          if (!i) {
            return [current];
          }
          return prev.concat(
            <b className="highlighted" key={value + current}>
              {value}
            </b>,
            current
          );
        }, [])}
      </span>
    );
  };

  return (
    <div className="candidates-table">
      <div style={{ overflowX: "auto",marginLeft:matches ? 36 : 72 }}>
        <table className="usersTable" style={{ width: "1017px" }}>
          <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
              .filter((n) =>
                (n.firstName + " " + n.lastName)
                  .toLowerCase()
                  .includes(search.toLowerCase())
              )
              .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).includes(search) ? (
                      formatLabel(candidate.firstName + " " + candidate.lastName, search)
                    ) : (
                      <span>{candidate.firstName + " " + candidate.lastName}</span>
                    )}
                  </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>
      </div>
      <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>
  );
};

TableViewPage.propTypes = {
  history: PropTypes.shape({
    replace: PropTypes.func,
    push: PropTypes.func,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }),
  }),
  setPage: PropTypes.func,
  page: PropTypes.number,
  search: PropTypes.string,
};

export default TableViewPage;
