import React, { useState, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import FilterButton from "../../components/Button/FilterButton";
import { useTheme } from "@mui/system";
import { useMediaQuery } from "@mui/material";
import userPageBtnIcon from "../../assets/images/userPageBtnIcon.png";
import PatternCard from "../../components/Patterns/PatternCard";
import { useDispatch, useSelector } from "react-redux";
import { setPatternsReq } from "../../store/actions/patterns/patternsActions";
import { selectPatterns } from "../../store/selectors/patternsSelectors";
import { selectProcesses } from "../../store/selectors/processesSelectors";
import { PATTERN_DETAILS_PAGE } from "../../constants/pages";
import CustomModal from "../../components/UI/CustomModal";
import plusIcon from "../../assets/images/plus.png";
import xIcon from "../../assets/images/x.png";
import { setProcessesReq } from "../../store/actions/processes/processesAction";
import { createPatternReq } from "../../store/actions/createPattern/createPatternActions";
import { updatePatternReq } from "../../store/actions/updatePattern/updatePatternActions";
import PatternFilters from "../../components/Patterns/PatternFilters";
import IconButton from "../../components/IconButton/IconButton";
import { Editor } from "@tinymce/tinymce-react";

const PatternsPage = ({ history }) => {
  const theme = useTheme();
  const matches = useMediaQuery(theme.breakpoints.down("sm"));
  const [isShownEdit, setIsShownEdit] = useState(false);
  const [openFilterDrawer, setOpenFilterDrawer] = useState(false);
  const [openAddPatternModal, setOpenAddPatternModal] = useState(false);
  const [openEditPatternModal, setOpenEditPatternModal] = useState(false);
  const [editPattern, setEditPattern] = useState(null);
  const [addPatternTitle, setAddPatternTitle] = useState("");
  const [addPatternCategory, setAddPatternCategory] = useState(1);
  const [selectionLevelFilter, setSelectionLevelFilter] = useState([]);
  const patterns = useSelector(selectPatterns);
  const processes = useSelector(selectProcesses);
  const dispatch = useDispatch();
  const addPatternEditor = useRef();
  const editPatternEditor = useRef();

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

  useEffect(() => {
    if (processes && processes.length > 0) {
      setAddPatternCategory(processes[0].id);
      const tmpSelectionLevelFilter = processes.map((level) => ({
        ...level,
        isChecked: false,
      }));
      setSelectionLevelFilter([...tmpSelectionLevelFilter]);
    }
  }, [processes]);

  const closeAddPatternModalHandler = () => {
    setOpenAddPatternModal(false);
  };

  const openEditModalHandler = (pattern) => {
    setEditPattern({
      id: pattern.id,
      title: pattern.title,
      createdAt: pattern.createdAt,
      selectionLevelId: pattern.selectionLevel.id,
      message: pattern.message,
    });
    setOpenEditPatternModal(true);
  };

  const closeEditPatternModalHandler = () => {
    setEditPattern(null);
    setOpenEditPatternModal(false);
  };

  const closeFilterDrawerHandler = () => {
    setOpenFilterDrawer(false);
  };

  const submitAddPatternHandler = (e) => {
    e.preventDefault();

    if (
      addPatternTitle.length === 0 ||
      addPatternEditor.current.getContent().length === 0
    ) {
      return;
    }

    dispatch(
      createPatternReq({
        title: addPatternTitle,
        selectionLevelId: addPatternCategory,
        message: addPatternEditor.current.getContent(),
      })
    );

    setOpenAddPatternModal(false);
    setAddPatternTitle("");
    setAddPatternCategory(processes[0].id);
  };

  const submitEditPatternHandler = (e) => {
    e.preventDefault();

    if (
      editPattern.title.length === 0 ||
      editPatternEditor.current.getContent() === 0
    ) {
      return;
    }

    dispatch(
      updatePatternReq({
        id: editPattern.id,
        title: editPattern.title,
        createdAt: editPattern.createdAt,
        selectionLevelId: editPattern.selectionLevelId,
        message: editPatternEditor.current.getContent(),
      })
    );

    setOpenEditPatternModal(false);
  };

  const handleFilterCheckboxes = (id) => {
    const tmpSelectionLevelFilter = selectionLevelFilter.map((level) =>
      level.id === id ? { ...level, isChecked: !level.isChecked } : level
    );
    setSelectionLevelFilter(tmpSelectionLevelFilter);
  };

  return (
    <div data-testid="patterns-page">
      <PatternFilters
        openFilterDrawer={openFilterDrawer}
        handleClose={closeFilterDrawerHandler}
        selectionLevelFilter={selectionLevelFilter}
        onChangeFilterCheckboxes={handleFilterCheckboxes}
      />
      {/* <CustomDrawer
        title="Šabloni"
        open={openFilterDrawer}
        onCloseDrawer={closeFilterDrawerHandler}
      >
        <form onSubmit={submitFiltersHandler}>
          <div className="custom-drawer">
            <div>
              <div className="custom-drawer-sub-card">
                <div className="custom-drawer-sub-card-label">
                  <p>Kategorija</p>
                </div>
                <div className="custom-drawer-sub-card-content">
                  <FormGroup>
                    {selectionLevelFilter.map((process) => (
                      <FormControlLabel
                        key={process.id}
                        control={
                          <Checkbox
                            value={process.name}
                            checked={process.isChecked}
                            onChange={handleFilterCheckboxes.bind(
                              this,
                              process.id
                            )}
                          />
                        }
                        label={process.name}
                      />
                    ))}
                  </FormGroup>
                </div>
              </div>
              <div className="custom-drawer-sub-card">
                <div className="custom-drawer-sub-card-label">
                  <p>Datum kreiranja</p>
                </div>
                <div className="custom-drawer-sub-card-content">
                  <FormGroup style={{ marginBottom: "9px" }}>
                    <label className="custom-drawer-sub-card-content-sub-label">
                      Od
                    </label>
                    <input
                      type="date"
                      onChange={(e) => setFromDate(e.target.value)}
                      value={fromDate}
                    />
                  </FormGroup>
                  <FormGroup>
                    <label className="custom-drawer-sub-card-content-sub-label">
                      Do
                    </label>
                    <input
                      type="date"
                      onChange={(e) => setToDate(e.target.value)}
                      value={toDate}
                    />
                  </FormGroup>
                </div>
              </div>
            </div>
            <div className="custom-drawer-submit">
              <button className="c-btn c-btn--primary">Pretrazi</button>
            </div>
          </div>
        </form>
      </CustomDrawer> */}
      <CustomModal
        open={openAddPatternModal}
        onCloseModal={closeAddPatternModalHandler}
        classes="add-pattern-modal"
      >
        <div className="add-pattern-modal-header">
          <div className="add-pattern-modal-header-title">
            <div className="add-pattern-modal-header-title-image">
              <img src={plusIcon} alt="plus" />
            </div>
            <div className="add-pattern-modal-header-title-title">
              <p>Dodavanje</p>
            </div>
            <div className="add-pattern-modal-header-title-sub">
              <sub> | Šablon</sub>
            </div>
          </div>
          <div
            className="add-pattern-modal-header-close"
            onClick={closeAddPatternModalHandler}
          >
            <img src={xIcon} alt="close" />
          </div>
        </div>
        <form onSubmit={submitAddPatternHandler}>
          <div className="add-pattern-modal-form-control">
            <label>Naslov</label>
            <input
              type="text"
              placeholder="ex. Datum HR intervjua"
              onChange={(e) => setAddPatternTitle(e.target.value)}
              value={addPatternTitle}
            />
          </div>
          <div className="add-pattern-modal-form-control">
            <label>Kategorija</label>
            <select
              name="add-pattern-category"
              value={addPatternCategory}
              onChange={(e) => setAddPatternCategory(e.target.value)}
            >
              {processes &&
                processes.map((process) => (
                  <option key={process.id} value={process.id}>
                    {process.name}
                  </option>
                ))}
            </select>
          </div>
          <div className="add-pattern-modal-form-control">
            <label>Tekst poruke</label>
            <Editor
              onInit={(evt, editor) => (addPatternEditor.current = editor)}
              style={{ height: "100px !important" }}
            />
            {/* <textarea
              rows="11"
              value={addPatternMessage}
              onChange={(e) => {
                if (e.target.value === "\n") {
                  setAddPatternMessage("<br>");
                } else {
                  setAddPatternMessage(e.target.value);
                }
              }}
            ></textarea> */}
          </div>
          <div className="add-pattern-modal-form-control">
            <input type="submit" value="DODAJ ŠABLON" />
          </div>
        </form>
      </CustomModal>
      <CustomModal
        open={openEditPatternModal}
        onCloseModal={closeEditPatternModalHandler}
        classes="edit-pattern-modal"
      >
        <div className="edit-pattern-modal-header">
          <div className="edit-pattern-modal-header-title">
            <div className="edit-pattern-modal-header-title-image">
              <img src={userPageBtnIcon} alt="plus" />
            </div>
            <div className="edit-pattern-modal-header-title-title">
              <p>Uređivanje</p>
            </div>
            <div className="edit-pattern-modal-header-title-sub">
              <sub> | Šablon</sub>
            </div>
          </div>
          <div
            className="edit-pattern-modal-header-close"
            onClick={closeEditPatternModalHandler}
          >
            <img src={xIcon} alt="close" />
          </div>
        </div>
        <form onSubmit={submitEditPatternHandler}>
          <div className="edit-pattern-modal-form-control">
            <label>Naslov</label>
            <input
              type="text"
              placeholder="ex. Datum HR intervjua"
              onChange={(e) =>
                setEditPattern((oldState) => ({
                  ...oldState,
                  title: e.target.value,
                }))
              }
              value={editPattern ? editPattern.title : ""}
            />
          </div>
          <div className="edit-pattern-modal-form-control">
            <label>Kategorija</label>
            <select
              name="edit-pattern-category"
              value={editPattern ? editPattern.selectionLevelId : 1}
              onChange={(e) =>
                setEditPattern((oldState) => ({
                  ...oldState,
                  selectionLevelId: e.target.value,
                }))
              }
            >
              {processes &&
                processes.map((process) => (
                  <option key={process.id} value={process.id}>
                    {process.name}
                  </option>
                ))}
            </select>
          </div>
          <div className="edit-pattern-modal-form-control">
            <label>Tekst poruke</label>
            <Editor
              initialValue={editPattern ? editPattern.message : ""}
              onInit={(evt, editor) => (editPatternEditor.current = editor)}
              style={{ height: "100px !important" }}
            />
            {/* <textarea
              rows="11"
              onChange={(e) =>
                setEditPattern((oldState) => ({
                  ...oldState,
                  message: e.target.value,
                }))
              }
              value={editPattern ? editPattern.message : ""}
            ></textarea> */}
          </div>
          <div className="edit-pattern-modal-form-control">
            <input type="submit" value="UREDI ŠABLON" />
          </div>
        </form>
      </CustomModal>
      <div className="patterns">
        <div className="patterns-header">
          <div>
            <h1>Napravljeni Šabloni</h1>
          </div>
          <div style={{ display: "flex" }}>
            <IconButton
              onClick={() => setIsShownEdit((oldState) => !oldState)}
              className={`c-btn--primary-outlined c-btn editEnableBtn userPageBtn ${
                isShownEdit && "pattern-header-active-button"
              }`}
            >
              {!matches && "Režim uređivanja"}
              <img
                style={{
                  position: "relative",
                  top: -0.25,
                  paddingLeft: matches ? "0px" : "10px",
                }}
                src={userPageBtnIcon}
              />
            </IconButton>
            <FilterButton onShowFilters={() => setOpenFilterDrawer(true)} />
          </div>
        </div>
        <div className="patterns-cards">
          {!patterns && (
            <div>
              <p>Loading...</p>
            </div>
          )}
          {patterns && patterns.length === 0 && (
            <div>
              <p>Trenutno nema dodatih sablona</p>
            </div>
          )}
          {patterns &&
            patterns.length > 0 &&
            patterns.map((pattern) => (
              <div className="pattern-card-parent" key={pattern.id}>
                <PatternCard
                  createdAt={pattern.createdAt}
                  title={pattern.title}
                  selectionProcess={pattern.selectionLevel.name}
                  onOpenEditModal={openEditModalHandler.bind(this, pattern)}
                  isShownEdit={isShownEdit}
                  onShowPatternDetails={() =>
                    history.push(
                      PATTERN_DETAILS_PAGE.replace(":id", pattern.id)
                    )
                  }
                />
              </div>
            ))}
        </div>
        <div className="patterns-button">
          <IconButton
            className="c-btn c-btn--primary add-ad-btn add-pattern-btn"
            onClick={() => setOpenAddPatternModal(true)}
          >
            Dodaj Šablon
          </IconButton>
        </div>
      </div>
    </div>
  );
};

PatternsPage.propTypes = {
  history: PropTypes.any,
};

export default PatternsPage;
