import {
  Button,
  IconButton,
  TextField
} from "@material-ui/core";
import React, { useEffect, useState } from "react";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import DeleteIcon from "@material-ui/icons/Delete";
import { Redirect } from "react-router";
import { logger } from "../../../services/monitoring";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useVehicleContext, VehicleProvider } from "../../Contexts/VehicleContext";
import { useUserContext } from "../../Contexts/UserContext";
import useStyles from "../../useStyles";

const MainForm = () => {
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const classes = useStyles();
  const [redirect, setRedirect] = useState(null);
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [carModel, setCarModel] = useState("");
  const [carTrim, setCarTrim] = useState("");
  const [carYear, setCarYear] = useState();
  const [flashpack, setFlashpack] = useState();
  const [mappingInputs, setMappingInputs] = useState([{ ecuName: "", ecuVersion: "" }]);
  const {
    addFlashpackVersion,
    busy,
  } = useVehicleContext();

  useEffect(() => {
    setTitle(`Add Flashpack Version`);
    setSitePath([
      {
        label: "Tools",
        link: "/tools/flashpacks",
      },
      {
        label: "Flashpack Versions",
        link: "/tools/flashpacks",
      },
      {
        label: `Add Flashpack Version`,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onCarModelChange = (event) => {
    setCarModel(event.target.value);
  }

  const onCarTrimChange = (event) => {
    setCarTrim(event.target.value);
  }

  const onCarYearChange = (event) => {
    setCarYear(event.target.value);
  }

  const onFlashpackChange = (event) => {
    setFlashpack(event.target.value);
  }

  const onSubmit = async (event) => {
    try {
      event.preventDefault();

      const carFlashpackVersions = []
      for (let i = 0; i < mappingInputs.length; i++) {
        mappingInputs[i] && mappingInputs[i].ecuName && mappingInputs[i].ecuVersion &&
          carFlashpackVersions.push({
            "car_ecu_name": mappingInputs[i].ecuName,
            "car_ecu_version": mappingInputs[i].ecuVersion,
          })
      }

      const result = await addFlashpackVersion(carModel, carTrim, parseInt(carYear), flashpack, carFlashpackVersions, token);
      if (!result || result.error) return;

      setMessage(`Added ${carYear} ${carModel} ${carTrim} ${flashpack}`);
      setRedirect(`/tools/flashpack/${carModel}/${carTrim}/${carYear}/${flashpack}`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

  if (redirect && redirect.length > 0) {
    return <Redirect to={redirect} />;
  }

  // code for handling the dynamic input fields adapted from
  // https://blog.stackademic.com/how-to-dynamically-add-input-fields-on-button-click-in-reactjs-ddf8d8fe495b

  const handleAddMappingInput = () => {
    setMappingInputs([...mappingInputs, { ecuName: "", ecuVersion: "", }]);
  };

  const handleChange = (event, index) => {
    let { name, value } = event.target;
    let onChangeValue = [...mappingInputs];
    onChangeValue[index][name] = value;
    setMappingInputs(onChangeValue);
  };

  const handleDeleteMappingInput = (index) => {
    const newArray = [...mappingInputs];
    newArray.splice(index, 1);
    setMappingInputs(newArray);
  };

  return (
    <div className={classes.paper}>
      <form className={classes.form} noValidate action="{onSubmit}">
        <div>
          <TextField
            id="carModel"
            name="carModel"
            label="Model"
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "255",
            }}
            required
            fullWidth
            value={carModel}
            onChange={onCarModelChange}
            type="text"
          />
          <TextField
            id="carTrim"
            name="carTrim"
            label="Trim"
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "255",
            }}
            required
            fullWidth
            value={carTrim}
            onChange={onCarTrimChange}
            type="text"
          />
          <TextField
            id="carYear"
            name="carYear"
            label="Year"
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "255",
            }}
            required
            fullWidth
            value={carYear}
            onChange={onCarYearChange}
            type="number"
          />
          <TextField
            id="flashpack"
            name="flashpack"
            label="Flashpack Number"
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "255",
            }}
            required
            fullWidth
            value={flashpack}
            onChange={onFlashpackChange}
            type="number"
          />
          <div className="container">
            {mappingInputs.map((item, index) => (
              <div className="input_container" key={index}>
                <TextField
                  id="ecuName"
                  name="ecuName"
                  label="ECU Name"
                  variant="outlined"
                  margin="normal"
                  inputProps={{
                    maxLength: "255",
                  }}
                  required
                  value={item.ecuName}
                  onChange={(event) => handleChange(event, index)}
                  type="text"
                />
                <TextField
                  id="ecuVersion"
                  name="ecuVersion"
                  label="ECU Version"
                  variant="outlined"
                  margin="normal"
                  inputProps={{
                    maxLength: "255",
                  }}
                  required
                  value={item.ecuVersion}
                  onChange={(event) => handleChange(event, index)}
                  type="text"
                />
                {mappingInputs.length > 1 && (
                  <IconButton
                    onClick={() => handleDeleteMappingInput(index)}
                    aria-label={`Delete`}
                    size="small"
                    color="primary"
                  >
                    <DeleteIcon aria-label={`Delete`} />
                  </IconButton>
                )}
                {index === mappingInputs.length - 1 && (
                  <IconButton
                    onClick={() => handleAddMappingInput()}
                    aria-label={`Add`}
                    size="small"
                    color="primary"
                  >
                    <AddCircleIcon aria-label={`Add`} />
                  </IconButton>
                )}
              </div>
            ))}
          </div>
        </div>
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Submitting..." : "Submit"}
        </Button>
      </form>
    </div>
  );
};

const FlashpackAdd = () => (
  <VehicleProvider>
    <MainForm />
  </VehicleProvider>
);

export default FlashpackAdd;