import React, { useEffect, useState } from "react";
import { Redirect, useParams } from "react-router";
import { useLocation } from "react-router-dom";

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 { updateFleetCANFilter, busy } = useFleetContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();
  const classes = useStyles();
  const queries = new URLSearchParams(useLocation().search);
  const canID = queries.get("can_id") ?? "";
  const [interval, setInterval] = useState(queries.get("interval") ?? "");
  const [edgeMask, setEdgeMask] = useState(queries.get("edge_mask") ?? "")
  const [redirect, setRedirect] = useState(null);


  useEffect(() => {
    const title = "Update 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 updateFleetCANFilter(name, canID, formData, token);
      if (!result || result.error) return;

      setMessage(`Updated 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}">
        <CANFilterFragment
          fleet={name}
          canId={canID}
          interval={interval}
          setInterval={setInterval}
          edgeMask={edgeMask}
          setEdgeMask={setEdgeMask}
          busy={busy}
          onSubmit={onSubmit}
        />
      </form>
    </div>
  );
};

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

export default FleetCANFilterUpdateForm;