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 { addFilter, busy } = useCANFiltersContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const [redirect, setRedirect] = useState(null);
  const classes = useStyles();
  const [canId, setCanId] = useState(undefined);
  const [interval, setInterval] = useState("");
  const [edgeMask, setEdgeMask] = useState("");
  const queries = new URLSearchParams(useLocation().search);
  const vin = queries.get("vin") ?? ""

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

  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const formData = {
        can_id: canId,
        interval: (interval == null || interval === "0") ? null:interval,
        edge_mask: edgeMask === "" ? null : edgeMask,
      };
      const result = await addFilter(vin, formData, token);
      if (!result || result.error) return;

      setMessage(`Added 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}
          setCanId={setCanId}
          interval={interval}
          setInterval={setInterval}
          edgeMask={edgeMask}
          setEdgeMask={setEdgeMask}
          busy={busy}
          onSubmit={onSubmit}
        />
      </form>
    </div>
  );
};

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

export default CANFilterCreate;