import React, { useEffect, useState } from "react";
import { Redirect, useParams } from "react-router";
import { TextField } from "@material-ui/core";

import { useUserContext } from "../../../../Contexts/UserContext";
import { useStatusContext } from "../../../../Contexts/StatusContext";
import { useFleetContext, FleetProvider } from "../../../../Contexts/FleetContext";
import useStyles from "../../../../useStyles";
import { logger } from "../../../../../services/monitoring";
import { CANFilterFragment } from "../../../../CANFilterEditFragment";


const MainForm = () => {
  const { name } = useParams();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const { addFleetCANFilter, busy } = useFleetContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();
  const classes = useStyles();
  const [canId, setCanId] = useState(undefined);
  const [interval, setInterval] = useState("");
  const [edgeMask, setEdgeMask] = useState("");
  const [redirect, setRedirect] = useState(null);

  useEffect(() => {
    const title = "Add CAN Filter"
    setTitle(title);
    setSitePath([
      {
        label: `Fleets`,
        link: "/fleets",
      },
      {
        label: `${name}`,
        link: `/fleet/${name}`
      },
      {
        label: title
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

      const formData = {
        can_id: canId,
        interval: (interval == null || interval === "") ? null : interval,
        edge_mask: edgeMask === "" ? null : edgeMask,
      };
      const result = await addFleetCANFilter(name, formData, token);
      if (!result || result.error) return;

      setMessage(`Added CAN filter ${result.can_id}`);
      setRedirect(`/fleet/${name}#filters`);
    } 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="name"
          name="name"
          label="Fleet Name"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "255",
            readOnly: true,
          }}
          value={name}
          required
          fullWidth
        />
        <CANFilterFragment
          fleet={name}
          canId={canId}
          setCanId={setCanId}
          interval={interval}
          setInterval={setInterval}
          edgeMask={edgeMask}
          setEdgeMask={setEdgeMask}
          busy={busy}
          onSubmit={onSubmit}
        />
      </form>
    </div>
  );
};

const FleetAddCANFilterForm = (props) => (
  <FleetProvider>
    <MainForm {...props} />
  </FleetProvider>
);

export default FleetAddCANFilterForm;