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

import {
  CANFiltersProvider,
  useCANFiltersContext,
} from "../../Contexts/CANFiltersContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { logger } from "../../../services/monitoring";
import {CANFilterFragment} from "../../CANFilterEditFragment";


const MainForm = () => {
  const { updateFilter, busy } = useCANFiltersContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [redirect, setRedirect] = useState(null);
  const classes = useStyles();
  const queries = new URLSearchParams(useLocation().search);
  const vin = queries.get("vin") ?? ""
  const canID = queries.get("can_id") ?? ""

  const [interval, setInterval] = useState(queries.get("interval") ?? "");
  const [edgeMask, setEdgeMask] = useState(queries.get("edge_mask") ?? "");

  useEffect(() => {
    setTitle("Update CAN Filter");
    setSitePath([
      {
        label: `Vehicle ${vin}`,
        link: "/vehicles",
      },
      {
        label: "Update CAN Filter",
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const formData = {
        can_id: canID,
        interval: interval,
        edge_mask: edgeMask,
      };
      const result = await updateFilter(vin, canID, formData, token);
      if (!result || result.error) return;

      setMessage(`Updated filter`);
      setRedirect(`/vehicle-status/${vin}#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
          vin={vin}
          canId={canID}
          interval={interval}
          setInterval={setInterval}
          edgeMask={edgeMask}
          setEdgeMask={setEdgeMask}
          busy={busy}
          onSubmit={onSubmit}
        />
      </form>
    </div>
  );
};

const CANFilterUpdate = (props) => (
  <CANFiltersProvider>
    <MainForm {...props} />
  </CANFiltersProvider>
);

export default CANFilterUpdate;