import React from "react";
import { useEffect, useState, useRef } from "react";
import { Link, useParams } from "react-router-dom";
import deleteImage from "../../../src/assets/images/delete.png";
import planeImage from "../../../src/assets/images/planeVectorBlue.png";
import IconButton from "../../components/IconButton/IconButton";
import { formatDateTime } from "../../util/helpers/dateHelpers";
import { setUsersReq } from "../../store/actions/users/usersActions";
import { createCandidateComment } from "../../store/actions/candidate/candidateActions";
import { useDispatch, useSelector } from "react-redux";
import { MentionsInput, Mention } from "react-mentions";
import { fetchCandidate } from "../../store/actions/candidate/candidateActions";
import { useMediaQuery } from "@mui/material";
import { useTheme } from "@mui/system";
import CandidateAd from '../../components/Candidates/CandidateAd';
import Slider from "react-slick";
import arrow_left from "../../assets/images/arrow_left.png";
import arrow_right from "../../assets/images/arrow_right.png";
import { ADS_PAGE } from "../../constants/pages";
import PropTypes from "prop-types";
import { deleteCandidate } from "../../request/candidatesRequest";

const CandidateDetailsPage = ({history}) => {
  const dispatch = useDispatch();
  const { users } = useSelector((s) => s.users);
  const { user } = useSelector((s) => s.user);
  const { candidate } = useSelector((s) => s.candidate);
  const [value, setValue] = useState("");
  let { id } = useParams();
  const messageContainer = useRef();
  const theme = useTheme();
  const matches = useMediaQuery(theme.breakpoints.down("680"));
  const adsSliderRef = useRef();

  useEffect(() => {
    dispatch(fetchCandidate({ id }));
    dispatch(setUsersReq());
  }, [dispatch]);

  useEffect(() => {
    messageContainer.current !== undefined
      ? (messageContainer.current.scrollTop =
          messageContainer.current.scrollHeight)
      : "";
  }, [messageContainer.current, candidate.comments]);

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const getArray = () => {
    let newArray = users.map(function (value) {
      return { id: value.id, display: value.firstName + value.lastName };
    });

    return newArray;
  };

  const tranformDisplay = (id, display) => {
    console.log(id);
    return "@" + display + " ";
  };

  const sendComment = () => {
    // can't send an empty message
    if (value.trim().length === 0) {
      return;
    }
    dispatch(
      createCandidateComment({
        content: value,
        userId: user.id,
        applicantId: parseInt(id),
        user: {
          id: user.id,
          firstName: user.firstName,
          lastName: user.lastName,
          email: user.email,
        },
      })
    );

    // var regex = /\[(.*?)\]/;
    // var matched = regex.exec(value);
    // user = matched[1];
    // let email = "dzenis1945@outlook.com";
    // let poruka = "dsadas";
    setValue("");
  };

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

  const getDummyAds = (len) => {
    const ads = [];

    for (let i = 0; i < 5 - len + 1; i++) {
      ads.push(<CandidateAd key={i} className="hiddenAd" />);
    }

    return ads;
  };

  const activeAdsArrowLeftHandler = () => {
    adsSliderRef.current.slickPrev();
  };

  const activeAdsArrowRightHandler = () => {
    adsSliderRef.current.slickNext();
  };

  const deleteCurrentCandidate = () => {
    dispatch(deleteCandidate({id}))
  }

  const navigateToDetailsPage = (id) => {
    history.push({
      pathname: ADS_PAGE + "/" + id,
      state: {
        from: history.location.pathname,
      },
    });
  }

  return (candidate && Object.keys(candidate).length === 0) ||
    user === undefined ? (
    <p>Loading...</p>
  ) : (
    <div className="main-candidate-container pl-144 pt-36px">
      <div className="l-t-rectangle"></div>
      <div className="r-b-rectangle"></div>
      <div className="top-candidate-container">
        <div>
          <p className="candidate-header">Kandidat</p>
          <span className="separation-line">|</span>
          <p className="candidate-lower-header">
            {candidate.firstName} {candidate.lastName}
          </p>
        </div>
        <div className="candidate-option-container">
          <IconButton className="c-btn c-btn--primary-outlined candidate-btn" onClick={deleteCurrentCandidate}>
            Obrisi
            <img src={deleteImage} alt="delete" className="candidates-image" />
          </IconButton>
        </div>
      </div>
      <div className="content-candidate-container">
        <div className="details-candidate-container">
          <p style={{ margin: 0 }}>
            {candidate.experience === 0
              ? "No experience"
              : "Experience:" + candidate.experience}
          </p>
          <div className="technologies-candidate-container">
            {candidate.technologyApplicants.map((obj, index) => (
              <div className="technology-candidate-card" key={index}>
                {obj.technology.name}
              </div>
            ))}
          </div>
          <div className="candidate-informations-container">
            <div className="candidate-informations-sub-container">
              <div className="candidate-property-container">
                <p className="informations-candidate-header">Kontakt</p>
                <p className="candidate-property">Email:</p>
                <p className="candidate-property">Telefon:</p>
              </div>
              <div
                style={{ alignSelf: "flex-end", marginLeft: 42 }}
                className="candidate-property-container"
              >
                <p className="candidate-property-value">{candidate.email}</p>
                <p className="candidate-property-value">
                  {candidate.phoneNumber}
                </p>
              </div>
            </div>
            <div className="candidate-informations-sub-container">
              <div className="candidate-property-container">
                <p className="informations-candidate-header">Drustvene mreze</p>
                <p className="candidate-property">Linkedln</p>
                <p className="candidate-property">GitHub</p>
                <p className="candidate-property">BitBucket</p>
              </div>
              <div
                style={{ alignSelf: "flex-end", marginLeft: 42 }}
                className="candidate-property-container"
              >
                <p className="candidate-property-value">
                  {candidate.linkedlnLink ?? "/"}
                </p>
                <p className="candidate-property-value">
                  {candidate.gitHubLink ?? "/"}
                </p>
                <p className="candidate-property-value">
                  {candidate.bitBucketLink ?? "/"}
                </p>
              </div>
            </div>
          </div>
        </div>
        <div className="comment-container">
          <div
            style={{
              minHeight: "219px",
              overflowX: "auto",
              paddingBottom: "10px",
              paddingTop: "10px",
            }}
            ref={messageContainer}
          >
            {candidate.comments.map((comment, index) => (
              <div className="comment-sub-container" key={index}>
                <div className="comment-sender">
                  <p>
                    {comment.user.firstName.charAt(0)}
                    {comment.user.lastName.charAt(0)}
                  </p>
                </div>
                <div className="comment-message">
                  <p className="comment-message-content">{comment.content}</p>
                  <p className="comment-message-date">
                    {formatDateTime(comment.dateOfSending)}
                  </p>
                </div>
              </div>
            ))}
          </div>
          <div className="comment-separation-line"></div>
          <div className="send-comment-container">
            <p>Komentar</p>
            <div className="send-comment-sub-container">
              <MentionsInput
                value={value}
                onChange={handleChange}
                className="comment-input"
                placeholder={"ex. Odlican kandidat"}
                style={{
                  input: !matches
                    ? { padding: 18, borderRadius: 7 }
                    : { padding: 9, borderRadius: 5 },
                  control: !matches
                    ? {
                        padding: 18,
                        color: "#fff",
                        suggestions: { list: { backgroundColor: "#F4F4F4" } },
                      }
                    : {
                        padding: 9,
                        color: "#fff",
                        suggestions: { list: { backgroundColor: "#F4F4F4" } },
                      },
                }}
              >
                <Mention
                  trigger="@"
                  className="comment-input-list"
                  data={getArray}
                  displayTransform={(id, display) =>
                    tranformDisplay(id, display)
                  }
                  markup="@[__display__]"
                  style={{ highlighter: { padding: 18, borderRadius: 7 } }}
                />
              </MentionsInput>
              <div className="comment-send-btn" onClick={sendComment}>
                <img
                  src={planeImage}
                  alt="plane"
                  className="candidates-image"
                />
                <p>Komentar</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className="applicant-ads-container">
        <p>Sve prijave</p>
        <div
          style={{ display: "flex", alignItems: "center", marginTop: "18px" }}
        >
          <div>
            {candidate.ads.length > 5 && (
              <div className="active-ads-ads-arrows">
                <button onClick={activeAdsArrowLeftHandler}>
                  <img src={arrow_left} alt="arrow-left" />
                </button>
                <button onClick={activeAdsArrowRightHandler}>
                  <img src={arrow_right} alt="arrow-right" />
                </button>
              </div>
            )}
          </div>
          <Slider {...settings} style={{ width: "100%" }} ref={adsSliderRef}>
            {candidate.ads.map((add, index) => (
              <CandidateAd
                add={add}
                key={index}
                onclick={() => navigateToDetailsPage(add.id)}
                className={index === 0 ? "" : "left-move-candidateAd"}
              />
            ))}
            {candidate.ads.length <= 5 && getDummyAds(candidate.ads.length)}
          </Slider>
        </div>
      </div>
      <div className="applicant-ads-buttons-container">
        <Link to="/candidates" className="applicant-ads-back-button">
          Nazad na sve kandidate
        </Link>
        <div className="applicant-cv-button">Preuzmi cv</div>
      </div>
    </div>
  );
};

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

export default CandidateDetailsPage;
