import React, { useEffect, useRef, useState } from "react";
import { Redirect } from "react-router";
import {
  Button,
  Checkbox,
  FormControlLabel,
  FormGroup,
  FormLabel,
  Radio,
  RadioGroup,
  TextField
} from "@material-ui/core";

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

const MainForm = () => {
  const { setMessage, setTitle, setSitePath } = useStatusContext();
  const { addFleet, busy } = useFleetContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const classes = useStyles();
  const [redirect, setRedirect] = useState(null);

  const nameEl = useRef(null);
  const [selectedLogLevel, setSelectedLogLevel] = useState("info");
  const [canbusEnabled, setCANBusEnabled] = useState(true);
  const [idpsEnabled, setIDPSEnabled] = useState(true);
  const [dataLoggerEnabled, setDataLoggerEnabled] = useState(false);
  const [maxMemBufferSize, setMaxMemBufferSize] = useState(0);
  const [maxDiskBufferSize, setMaxDiskBufferSize] = useState(0);

  useEffect(() => {
    setTitle("Add Fleet");
    setSitePath([
      {
        label: "Fleets",
        link: "/fleets",
      },
      {
        label: "Add Fleet",
      },
    ]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onLogLevelChange = (event) => {
    setSelectedLogLevel(event.target.value);
  }

  const onCANBusChange = (event) => {
    setCANBusEnabled(event.target.checked);
  }

  const onIDPSChange = (event) => {
    setIDPSEnabled(event.target.checked);
  }

  const onDataLoggerChange = (event) => {
    setDataLoggerEnabled(event.target.checked);
  }

  const onMaxMemBufferSizeChange = (event) => {
    setMaxMemBufferSize(event.target.value);
  }

  const onMaxDiskBufferSizeChange = (event) => {
    setMaxDiskBufferSize(event.target.value);
  }

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

      const formData = {
        name: nameEl.current.value,
        log_level: selectedLogLevel,
        canbus: {
          enabled: canbusEnabled,
          data_logger_enabled: canbusEnabled ? dataLoggerEnabled : false,
          max_mem_buffer_size: canbusEnabled ? parseInt(maxMemBufferSize) : 0,
          max_disk_buffer_size: canbusEnabled && dataLoggerEnabled ? parseInt(maxDiskBufferSize) : 0
        },
        idps_enabled: idpsEnabled,
      };
      const result = await addFleet(formData, token);
      if (!result || result.error) return;

      setMessage(`Added ${result.name}`);
      setRedirect(`/fleets`);
    } 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="Name"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "17",
          }}
          required
          fullWidth
          inputRef={nameEl}
        />
        <FormLabel id="demo-row-radio-buttons-group-label">Log Level</FormLabel>
        <RadioGroup
          row
          aria-labelledby="demo-row-radio-buttons-group-label"
          name="log-level-group"
          value={selectedLogLevel}
          onChange={onLogLevelChange}
          margin="normal"
        >
          <FormControlLabel value="trace" control={<Radio />} label="Trace" />
          <FormControlLabel value="debug" control={<Radio />} label="Debug" />
          <FormControlLabel value="info" control={<Radio />} label="Info" />
          <FormControlLabel value="warning" control={<Radio />} label="Warning" />
          <FormControlLabel value="error" control={<Radio />} label="Error" />
          <FormControlLabel value="critical" control={<Radio />} label="Critical" />
        </RadioGroup>
        <FormLabel id="demo-row-radio-buttons-group-label">CAN Bus</FormLabel>
        <FormGroup>
          <FormControlLabel control={
            <Checkbox
              checked={canbusEnabled}
              onChange={onCANBusChange}
            />
          } label="CAN Bus Enabled" />
          <TextField
            id="max_mem_buffer_size"
            name="max_mem_buffer_size"
            label='Max Memory Buffer Size (0 uses default size)'
            value={maxMemBufferSize}
            onChange={onMaxMemBufferSizeChange}
            variant="outlined"
            margin="normal"
            inputProps={{
              maxLength: "12",
            }}
            type="number"
            disabled={!canbusEnabled}
            required
            fullWidth
          />
          <FormControlLabel control={
            <Checkbox
              checked={dataLoggerEnabled}
              onChange={onDataLoggerChange}
              disabled={!canbusEnabled}
            />
          } label="Data Logger Enabled" />
        </FormGroup>
        <TextField
          id="max_disk_buffer_size"
          name="max_disk_buffer_size"
          label='Max Disk Buffer Size (0 uses default size)'
          value={maxDiskBufferSize}
          onChange={onMaxDiskBufferSizeChange}
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "12",
          }}
          type="number"
          disabled={!dataLoggerEnabled}
          required
          fullWidth
        />
        <FormControlLabel control={
          <Checkbox
            checked={idpsEnabled}
            onChange={onIDPSChange}
          />
        } label="IDPS Enabled" />
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Submitting..." : "Submit"}
        </Button>
      </form>
    </div>
  );
};

const FleetAddForm = () => (
  <FleetProvider>
    <MainForm />
  </FleetProvider>
);

export default FleetAddForm;
