import React, { useEffect, useState } from "react";
import { IconButton } from "@mui/material";
import { Link } from "react-router-dom";
import plusIcon from "../../assets/images/plus.png";
import sendMessage from "../../assets/images/send_message.png";
import { useParams } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { setPatternReq } from "../../store/actions/pattern/patternActions";
import { selectPattern } from "../../store/selectors/patternSelectors";
import {
  clearNotSentEmailsArray,
  scheduleAppointmentReq,
} from "../../store/actions/scheduleAppointment/scheduleAppointmentActions";
import { selectNotSentEmails } from "../../store/selectors/scheduleAppointmentSelectors";
import { setPatternApplicantsReq } from "../../store/actions/patternApplicants/patternApplicantsActions";
import { selectPatternApplicants } from "../../store/selectors/patternApplicants";
import { PATTERNS_PAGE } from "../../constants/pages";
import { useHistory } from "react-router-dom";

const PatternDetailsPage = () => {
  const [emails, setEmails] = useState([]);
  const [email, setEmail] = useState("");
  const pattern = useSelector(selectPattern);
  const patternApplicants = useSelector(selectPatternApplicants);
  const notSentEmails = useSelector(selectNotSentEmails);
  const [selectedPatternApplicants, setSelectedPatternApplicants] = useState(
    []
  );
  const { id } = useParams();
  const dispatch = useDispatch();
  const history = useHistory();

  const navigateToPatternsPage = () => {
    history.push(PATTERNS_PAGE);
  };

  useEffect(() => {
    setSelectedPatternApplicants(patternApplicants);
  }, [patternApplicants]);

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

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

  useEffect(() => {
    if (patternApplicants.length > 0) {
      setEmail(patternApplicants[0].email);
    }
  }, [patternApplicants]);

  useEffect(() => {
    const arrOfApplicants = [];
    for (let i = 0; i < patternApplicants.length; i++) {
      let s = 0;
      for (let j = 0; j < emails.length; j++) {
        if (patternApplicants[i].email === emails[j]) s = 1;
      }

      if (s === 0) arrOfApplicants.push(patternApplicants[i]);
    }

    setSelectedPatternApplicants(arrOfApplicants);
    if (arrOfApplicants.length > 0) {
      setEmail(arrOfApplicants[0].email);
    }
  }, [emails]);

  useEffect(() => {
    dispatch(clearNotSentEmailsArray());
  }, []);

  const addNewEmailHandler = () => {
    if (email.length === 0) return;
    if(selectedPatternApplicants.length === 0) return;
    setEmails((oldState) => [...oldState, email]);
    setEmail("");
  };

  const scheduleAppointmentHandler = () => {
    dispatch(
      scheduleAppointmentReq({
        emails,
        patternId: id,
        handleApiResponseSuccess: navigateToPatternsPage,
      })
    );
  };

  return (
    <>
      {!pattern && (
        <div>
          <p>Loading...</p>
        </div>
      )}
      {pattern && (
        <div className="pattern-details">
          <div className="pattern-details-header">
            <p>
              <span>Napravljen:</span>{" "}
              {new Date(pattern.createdAt).toLocaleDateString()}
            </p>
          </div>
          <div className="pattern-details-card">
            <div className="pattern-details-card-title">
              <div className="pattern-details-card-title-title">
                <h1>Šablon</h1>
              </div>
              <div className="pattern-details-card-title-sub">
                <sub> | Zakazivanje termina</sub>
              </div>
            </div>
            <div className="pattern-details-card-sub-card">
              <div className="pattern-details-card-sub-card-title">
                <p>{pattern.selectionLevel.name}</p>
              </div>
              <div className="pattern-details-card-sub-card-emails">
                {emails &&
                  emails.map((email, index) => (
                    <div
                      key={index}
                      className="pattern-details-card-sub-card-emails-email"
                    >
                      {email}
                    </div>
                  ))}
              </div>
            </div>

            <div className="pattern-details-card-sub-card">
              <div className="pattern-details-card-sub-card-title">
                <p>{pattern.selectionLevel.name}</p>
              </div>
              <div className="pattern-details-card-sub-card-add-email">
                <select onChange={(e) => setEmail(e.target.value)}>
                  {selectedPatternApplicants.length > 0 &&
                    selectedPatternApplicants.map((applicant) => (
                      <option
                        key={applicant.applicantId}
                        value={applicant.email}
                      >
                        {applicant.firstName + " " + applicant.lastName}
                      </option>
                    ))}
                </select>
                <button onClick={addNewEmailHandler}>
                  <img src={plusIcon} alt="plus" />
                </button>
              </div>
            </div>

            {notSentEmails && notSentEmails.map((x) => <p key={x}>{x}</p>)}

            <div className="pattern-details-card-sub-card">
              <div className="pattern-details-card-sub-card-title">
                <p>Teskt poruke</p>
              </div>
              <div className="pattern-details-card-sub-card-message-pattern">
                <textarea disabled value={pattern.message}></textarea>
              </div>
            </div>

            <div className="pattern-details-card-buttons">
              <Link className="ad-details-buttons-link" to="/patterns">
                Nazad na sve šablone
              </Link>
              <IconButton
                disabled={emails.length === 0}
                className="c-btn c-btn--primary add-ad-btn"
                onClick={scheduleAppointmentHandler}
              >
                <img
                  style={{
                    marginRight: "5px",
                    width: "12px",
                    height: "12px",
                  }}
                  src={sendMessage}
                />
                PORUKU
              </IconButton>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default PatternDetailsPage;
