import React, { useState } from "react";
import PropType from "prop-types";
import Box from "@mui/material/Box";
import Drawer from "@mui/material/Drawer";
import FormGroup from "@mui/material/FormGroup";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import Slider from "@mui/material/Slider";
import filterIcon from "../../assets/images/filter_vector.png";
import x from "../../assets/images/x.png";
import { filterCandidates } from "../../store/actions/candidates/candidatesActions";
import { useDispatch } from "react-redux";
import { formatDateInput } from "../../util/helpers/dateHelpers";

const CandidateFilters = ({ open, handleClose,pageSize,currentPage }) => {
  const dispatch = useDispatch();
  const [sliderValue, setSliderValue] = useState([0, 0]);
  const [startingDate,setStartingDate] = useState('')
  const [endingDate,setEndingDate] = useState('')
  const [technologies, setTechnologies] = useState([
    { name: "react", isChecked: false },
    { name: "angular", isChecked: false },
    { name: "sql", isChecked: false },
    { name: "nodejs", isChecked: false },
    { name: ".net", isChecked: false },
    { name: "git", isChecked: false },
    { name: "html/css", isChecked: false },
    { name: "vanillaJS", isChecked: false },
  ]);
  const [typesOfEmployments, setTypesOfEmployments] = useState([
    { name: "Posao", isChecked: true },
    { name: "Intership", isChecked: false },
  ]);

  const handleSliderChange = (_, newValue) => {
    setSliderValue(newValue);
  };

  const updateState = (name, value) => {
    const newState = technologies.map((obj) => {
      if (obj.name === name) {
        return { ...obj, isChecked: value };
      }
      return obj;
    });
    setTechnologies(newState);
  };

  const updateTypeState = (name, value) => {
    const newState = typesOfEmployments.map((obj) => {
      if (obj.name === name) {
        return { ...obj, isChecked: value };
      } else {
        return { ...obj, isChecked: false };
      }
    });
    setTypesOfEmployments(newState);
  };

  const handleTechologiesChange = (event) => {
    updateState(event.target.name, event.target.checked);
  };

  const getSelectedEmploymentType = () => {
    return typesOfEmployments.filter((e) => e.isChecked === true);
  };

  const getSelectedTechnologies = () => {
    let k = technologies.filter(t => t.isChecked === true)
    let n = []
    k.forEach(technology => {
      n.push(technology.name)
    });

    return n;
  }

  const handleChangeTypeOfEmployment = (name) => {
    updateTypeState(name, true);
  };

  const handleApiResponseSuccess = () => {
    handleClose()
  }

  const fiterItems = () => {
    dispatch(
      filterCandidates({
        pageSize,
        currentPage,
        minExperience: sliderValue[0],
        maxExperience: sliderValue[1],
        employmentType: getSelectedEmploymentType()[0].name,
        minDateOfApplication:startingDate,
        maxDateOfApplication:endingDate,
        technologies:getSelectedTechnologies(),
        handleApiResponseSuccess
      })
    );
  };

  const handleChangeStartingDate = (event) => {
    console.log(event)
    setStartingDate(event.target.value)
  }

  const handleChangeEndingDate = (event) => {
    console.log(event)
    setEndingDate(event.target.value)
  }

  const getDayBeforeToday = (date = new Date()) => {
    const previous = new Date(date.getTime());
    previous.setDate(date.getDate() - 1);
    return previous;
  }

  const list = () => (
    <Box
      sx={{
        width: 360,
        height: "100%",
        borderRadius: "18px 0 0 18px",
        padding: "36px",
      }}
      role="presentation"
      onKeyDown={handleClose}
    >
      <div>
        <div className="ad-filters-header-container">
          <div className="ad-filters-header">
            <img src={filterIcon} alt="filter_icon" />
            <h3>Filteri</h3>
            <p>
              <sub>| Kandidati</sub>
            </p>
          </div>
          <div className="ad-filters-header-close" onClick={handleClose}>
            <img src={x} alt="x" />
          </div>
        </div>
        <div className="ad-filters-experience">
          <div className="ad-filters-sub-title">
            <p>Godine iskustva</p>
          </div>
          <div className="ad-filters-experience-slider">
            <Slider
              getAriaLabel={() => "Temperature range"}
              value={sliderValue}
              onChange={handleSliderChange}
              valueLabelDisplay="auto"
              max={20}
            />
          </div>
        </div>
        <div className="ad-filters-technologies">
          <div className="ad-filters-sub-title">
            <p>Tehnologije</p>
          </div>
          <div className="ad-filters-technologies-checkboxes">
            <FormGroup>
              {technologies.map((technology, index) => (
                <FormControlLabel
                  key={index}
                  control={
                    <Checkbox
                      checked={technology.isChecked}
                      name={technology.name}
                      onChange={handleTechologiesChange}
                    />
                  }
                  label={technology.name}
                />
              ))}
            </FormGroup>
          </div>
        </div>
        <div className="ad-filters-technologies">
          <div className="ad-filters-sub-title">
            <p>Tip zaposlenja</p>
          </div>
          <div className="ad-filters-employment-type">
            {typesOfEmployments.map((type, index) => (
              <button
                key={index}
                className={
                  type.isChecked === false
                    ? "c-btn c-btn--primary-outlined"
                    : "c-btn c-btn--primary"
                }
                onClick={() => handleChangeTypeOfEmployment(type.name)}
              >
                {type.name}
              </button>
            ))}
          </div>
        </div>
        <div className="ad-filters-technologies" style={{ marginTop: "35px" }}>
          <div className="ad-filters-sub-title">
            <p>Datum prijave</p>
            <div className="filter-date-container">
              <p>Od</p>
              <input type="date" id="start" max={formatDateInput(getDayBeforeToday())} value={startingDate} onChange={handleChangeStartingDate}/>
            </div>
            <div className="filter-date-container">
              <p>Do</p>
              <input type="date" id="start" max={ formatDateInput(new Date())} value={endingDate} onChange={handleChangeEndingDate}/>
            </div>
          </div>
        </div>
        <div className="ad-filters-search" style={{ marginTop: "45px" }}>
          <button className="c-btn c-btn--primary" onClick={fiterItems}>
            Pretrazi
          </button>
        </div>
      </div>
    </Box>
  );

  return (
    <div>
      <Drawer anchor="right" open={open} onClose={handleClose}>
        {list()}
      </Drawer>
    </div>
  );
};

CandidateFilters.propTypes = {
  open: PropType.any,
  handleClose: PropType.func,
  candidates: PropType.array,
  currentPage:PropType.number,
  pageSize:PropType.number
};

export default CandidateFilters;
