import {
  Button,
  TextField
} from "@material-ui/core";
import ECUDropDown from "../../Controls/ECUDropDown";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
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 { model, trim, year, flashpack } = useParams();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const classes = useStyles();
  const [redirect, setRedirect] = useState(null);
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [ecuName, setECUName] = useState("");
  const [ecuVersion, setECUVersion] = useState("");
  const {
    addFlashpackVersionECUMapping,
    busy,
  } = useVehicleContext();

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

  const onCarECUNameChange = (event) => {
    let newECU = event.target.value

    setECUName(newECU)
  }

  const onCarECUVersionChange = (event) => {
    let newECUVersion = event.target.value

    setECUVersion(newECUVersion)
  }

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

      const result = await addFlashpackVersionECUMapping(model, trim, parseInt(year), flashpack, ecuName, ecuVersion, token);
      if (!result || result.error) return;

      setMessage(`Added ${year} ${model} ${trim} ${flashpack} ${ecuName} ${ecuVersion}`);
      setRedirect(`/tools/flashpack/${model}/${trim}/${year}/${flashpack}`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };

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

  return (
    <div className={classes.paper}>
      <form className={classes.form} noValidate action="{onSubmit}">
        <div>
          <ECUDropDown
            id="ecuName"
            name="ecuName"
            label="ECU Name"
            value={ecuName}
            changeHandler={(event) => onCarECUNameChange(event)}
            required
          />
          <TextField
            id="ecuVersion"
            name="ecuVersion"
            label="ECU Version"
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "255",
            }}
            required
            value={ecuVersion}
            onChange={(event) => onCarECUVersionChange(event)}
            type="text"
          />
        </div>
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Submitting..." : "Submit"}
        </Button>
      </form >
    </div >
  );
};

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

export default FlashpackECUMappingAdd;