import {
  Button,
  TextField
} from "@material-ui/core";
import { useParams } from "react-router";
import React, { useEffect, useState } from "react";
import { Redirect } from "react-router";
import { logger } from "../../../services/monitoring";
import { useStatusContext } from "../../Contexts/StatusContext";
import {
  CarUpdatesProvider,
  useCarUpdatesContext
} from "../../Contexts/CarUpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import useStyles from "../../useStyles";

const MainForm = () => {
  const { addSUMSVersionRxSwins, busy } = useCarUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const classes = useStyles();
  const [redirect, setRedirect] = useState(null);
  const { sums_version } = useParams();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [rxswin, setRxswin] = useState("");

  useEffect(() => {
    setTitle(`Add RXSWIN to SUMS Version ${sums_version}`);
    setSitePath([
      {
        label: "Tools",
        link: "/tools/sumsversions",
      },
      {
        label: "SUMS Versions",
        link: "/tools/sumsversions",
      },
      {
        label: `SUMS Version ${sums_version}`,
        link: `/tools/sums/${sums_version}`,
      },
      {
        label: `Add RXSWIN`,
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onRxswinChange = (event) => {
    setRxswin(event.target.value);
  }

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

      const data = {
        "swversion_rxswins": [
          {
            "version": sums_version,
            "rxswin": rxswin,
          },
        ],
      };

      const result = await addSUMSVersionRxSwins(sums_version, data, token);
      if (!result || result.error) return;

      setMessage(`Added ${rxswin}`);
      setRedirect(`/tools/sums/${sums_version}`);
    } 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}">
        <TextField
          id="rxswin"
          name="rxswin"
          label="RX Software Identification Number (RXSWIN)"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "255",
          }}
          required
          fullWidth
          value={rxswin}
          onChange={onRxswinChange}
          type="text"
        />
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Submitting..." : "Submit"}
        </Button>
      </form>
    </div>
  );
};

const SumsRxSwinAdd = () => (
  <CarUpdatesProvider>
    <MainForm />
  </CarUpdatesProvider>
);

export default SumsRxSwinAdd;