import {
  Button,
  IconButton,
  TextField
} from "@material-ui/core";
import ECUDropDown from "../../Controls/ECUDropDown";
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 { useLocalStorage } from "../../useLocalStorage";
import useStyles from "../../useStyles";
import { DropDownList } from "../../Controls/DropDownList";
import modelsTrimsYears from '.././modelsTrimsYears.json';

const MainForm = () => {
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const classes = useStyles();
  const [redirect, setRedirect] = useState(null);
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [carModel, setCarModel] = useLocalStorage("FLASHPACK_ADD_MODEL", "Ocean");
  const [carTrim, setCarTrim] = useLocalStorage("FLASHPACK_ADD_TRIM", "Sport");
  const [carYear, setCarYear] = useLocalStorage("FLASHPACK_ADD_YEAR", 2024);
  const [trims, setTrims] = useLocalStorage("FLASHPACK_ADD_TRIMS", modelsTrimsYears.oceanTrims);
  const [years, setYears] = useLocalStorage("FLASHPACK_ADD_YEARS", modelsTrimsYears.oceanYears);
  const [flashpack, setFlashpack] = useState("");
  const [osVersion, setOSVersion] = useState("");
  const [mappingInputs, setMappingInputs] = useState([{ ecuName: "", ecuVersion: "" }]);
  const {
    addFlashpackVersion,
    getOSVersions,
    osVersions,
    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
  }, []);

  useEffect(() => {
    (async () => {
      try {
        if (!token) return;
        await getOSVersions(token);
      } catch (e) {
        setMessage(e.message);
        logger.warn(e.stack);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  const onCarModelChange = (event) => {
    let newModel = event.target.value

    setCarModel(newModel)

    switch (newModel) {
      case "Ocean":
        setTrims(modelsTrimsYears.oceanTrims);
        setYears(modelsTrimsYears.oceanYears);
        break;
      default:
        break;
    }
  }

  const onCarTrimChange = (event) => {
    let newTrim = event.target.value

    setCarTrim(newTrim)
  }

  const onCarYearChange = (event) => {
    let newYear = event.target.value

    setCarYear(newYear)
  }

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

  const onOSVersionChange = (event) => {
    setOSVersion(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, osVersion, 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>
          <DropDownList fullWidth required label="Model" data={modelsTrimsYears.models} classes={classes} onChange={onCarModelChange} value={carModel} />
          <DropDownList fullWidth required label="Trim" data={trims} disabled={!carModel || !trims} classes={classes} onChange={onCarTrimChange} value={carTrim} />
          <DropDownList fullWidth required label="Year" data={years} disabled={!carModel || !years} classes={classes} onChange={onCarYearChange} value={carYear} />
          <TextField
            id="flashpack"
            name="flashpack"
            label="Flashpack Number"
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "255",
            }}
            required
            fullWidth
            value={flashpack}
            onChange={onFlashpackChange}
            type="number"
          />
          <DropDownList fullWidth required label="OS Version" data={osVersions} classes={classes} onChange={onOSVersionChange} value={osVersion} />
          <div className="container">
            {mappingInputs.map((item, index) => (
              <div className="input_container" key={index}>
                <ECUDropDown
                  id="ecuName"
                  name="ecuName"
                  label="ECU Name"
                  value={item.ecuName}
                  changeHandler={(event) => handleChange(event, index)}
                  required
                />
                <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;