import React, { useEffect, useState } from "react";
import { Redirect, useParams } from "react-router";
import {
  Box,
  Button,
  Checkbox,
  FormControlLabel,
  FormGroup,
  FormLabel,
  Radio,
  RadioGroup,
  TextField,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Typography,
} 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";
import { VehicleProvider } from "../../../../Contexts/VehicleContext";
import CarSelectionTable from "../../../../Controls/CarSelectionTable";
import SearchField from "../../../../Controls/SearchField";

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

  const [vins, setVins] = useState([]);
  const [search, setSearch] = useState("");
  const [selectedLogLevel, setSelectedLogLevel] = useState("info");
  const [canbusEnabled, setCANBusEnabled] = useState(true);
  const [dataLoggerEnabled, setDataLoggerEnabled] = useState(false);
  const [maxMemBufferSize, setMaxMemBufferSize] = useState(0);
  const [maxDiskBufferSize, setMaxDiskBufferSize] = useState(0);

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

  const handleSearch = (query) => {
    setVins([]);
    setSearch(query);
  };

  const handleSelectAll = (cars) => {
    setVins(cars);
  };

  const handleSelect = (event, key) => {
    try {
      let newVins;
      if (event.target.checked) {
        newVins = [...vins];
        newVins.push(key);
      } else {
        newVins = vins.filter((vin) => vin !== key);
      }
      setVins(newVins);
    } catch (e) {
      logger.warn(e.stack);
    }
  };

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

  const onCANBusChange = (event) => {
    setCANBusEnabled(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) => {
    event.preventDefault();

    try {
      const formData = {
        vins,
        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
        }
      };

      const result = await addFleetVehicles(name, formData, token);

      setMessage(`Added ${result.vins.join(", ")}`);
      setRedirect(`/fleet/${name}#vehicles`);
    } 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}">
        <SearchField classes={classes} onSearch={handleSearch}/>
        <VehicleProvider sx={{ height: "auto" }}>
          <CarSelectionTable
            classes={classes}
            token={token}
            multiSelect={true}
            search={{search}}
            selected={vins}
            onSelect={handleSelect}
            onSelectAll={handleSelectAll}
          />
        </VehicleProvider>

        <Box className={classes.fleetVehicleAddSubmit}>
          <Accordion>
            <AccordionSummary>
              <Typography>Additional Options</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Box sx={{ width: "100%" }}>
                <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
                  />
              </Box>
            </AccordionDetails>
          </Accordion>
          
          <Button
            type="submit"
            disabled={busy}
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={onSubmit}
          >
            {busy ? "Submitting..." : "Submit"}
          </Button>
        </Box>
      </form>
    </div>
  );
};

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

export default FleetAddVehicleForm;
