import React from "react";
import PropTypes from "prop-types";
import { selectDoneProcessError } from "../../store/selectors/processSelectors";
import { selectAuthUser } from "../../store/selectors/userSelectors";
import { setDoneProcessReq } from "../../store/actions/processes/processAction";
import { useDispatch, useSelector } from "react-redux";
import { formatDateSrb, formatTimeSrb } from "../../util/helpers/dateHelpers";
import { SELECTION_PROCESS_OF_APPLICANT_PAGE } from "../../constants/pages";
import { PUT_PROCESS_LOADING } from "../../store/actions/processes/processesActionConstants";
import { selectIsLoadingByActionType } from "../../store/selectors/loadingSelectors";
import Backdrop from "../../components/MUI/BackdropComponent";
import { IconButton } from "@mui/material";
import plus from "../../assets/images/plus.png";

const dragStart = (e, applicant) => {
  e.dataTransfer.setData("text/plain", JSON.stringify(applicant));
};

const dragOver = (e) => {
  e.preventDefault();
};

const Selection = (props) => {
  const allApplicants = props.selection.selectionProcesses;
  const errorMessage = useSelector(selectDoneProcessError);
  const dispatch = useDispatch();
  const user = useSelector(selectAuthUser);

  const dropItem = (e, selId) => {
    var data = e.dataTransfer.getData("text/plain");
    const selectionProcess = JSON.parse(data);
    if (selectionProcess.selectionLevelId < selId) {
      dispatch(
        setDoneProcessReq({
          id: selectionProcess.id,
          name: "Some random name",
          applicantId: selectionProcess.applicant.applicantId,
          schedulerId: user.id,
        })
      );
    }
    if (errorMessage) {
      console.log(errorMessage);
    }
  };

  const isLoading = useSelector(
    selectIsLoadingByActionType(PUT_PROCESS_LOADING)
  );

  const handleOpenDetails = (id) => {
    props.history.push(SELECTION_PROCESS_OF_APPLICANT_PAGE.replace(":id", id));
  };
  const applicants = allApplicants?.filter((a) => a.status !== "Odrađen");
  const renderList = applicants?.map((item, index) => {
    return (
      <div
        draggable
        key={index}
        className="sel-item"
        onDragStart={(e) => dragStart(e, item)}
        onClick={() => handleOpenDetails(item.applicant.applicantId)}
      >
        <div className="status">
          <button>{item.status}</button>
        </div>
        <div className="date-name">
          <div className="date">
            {item.date !== null && item.date !== "" && (
              <p>
                {formatDateSrb(item.date)} <span className="grey">|</span>{" "}
                {formatTimeSrb(item.date)}
              </p>
            )}
          </div>
          <div className="full-name">
            <p>{item.applicant.firstName + " " + item.applicant.lastName}</p>
          </div>
        </div>
      </div>
    );
  });

  return (
    <div
      data-testid="selection-level"
      dropppable="true"
      id={props.selection.id}
      className="selection-card"
      onDragOver={(e) => dragOver(e)}
      onDrop={(e) => dropItem(e, props.selection.id)}
    >
      <div className="selection-card-title">
        <h3>{props.selection.name}</h3>
        {props.order === 0 ? (
          <IconButton
            className={`c-btn--primary-outlined c-btn td-btn`}
            onClick={props.modalEvent}
          >
            <img
              style={{
                position: "relative",
              }}
              src={plus}
            />
          </IconButton>
        ) : (
          ""
        )}
      </div>
      <Backdrop position="absolute" isLoading={isLoading} />

      {applicants &&
        applicants !== null &&
        applicants?.length > 0 &&
        renderList}
      {applicants && applicants !== null && applicants?.length === 0 && (
        <div className="sel-item-no-data">
          <div className="date">
            <p>Nema kandidata u selekciji</p>
          </div>
        </div>
      )}
    </div>
  );
};

Selection.propTypes = {
  history: PropTypes.shape({
    replace: PropTypes.func,
    push: PropTypes.func,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }),
  }),
  order: PropTypes.number,
  modalEvent: PropTypes.func,
  selection: PropTypes.shape({
    id: PropTypes.number,
    name: PropTypes.string,
    selectionProcesses: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.number,
        name: PropTypes.string,
        date: PropTypes.string,
        status: PropTypes.string,
        currentSelection: PropTypes.number,
        map: PropTypes.func,
        applicant: PropTypes.shape({
          firstName: PropTypes.string,
          lastName: PropTypes.string,
        }),
      })
    ),
  }),
};

export default Selection;
