import React, {useEffect, useState} from "react";
import PropTypes from "prop-types";
import {Button, FormControl, InputLabel, Select} from "@material-ui/core";

import {useVehicleContext} from "../../Contexts/VehicleContext";
import commands from "./Commands";
import useStyles from "../../useStyles";
import {useUserContext} from "../../Contexts/UserContext";
import {useStatusContext} from "../../Contexts/StatusContext";
import {logger} from "../../../services/monitoring";
import {Parameters} from "./Parameters";
import clsx from "clsx";
import {sanitize} from "./sanitize";

const SendCommand = ({vins}) => {
  const classes = useStyles();
  const {busy, sendCommand} = useVehicleContext();
  const {
    token: {
      idToken: {jwtToken: token},
    },
  } = useUserContext();
  const {setMessage} = useStatusContext();
  const [command, setCommand] = useState("");
  const [parameters, setParameters] = useState(null);
  const [data, setData] = useState(null);
  const [startTime, setStartTime] = useState(null)
  const [endTime, setEndTime] = useState(null)

  const changeCommandHandler = (e) => {
    selectCommand(e.target.value);
  };

  const selectCommand = (cmd) => {
    const params = getParameters(cmd);
    setCommand(cmd);
    setParameters(params);
    setData(null);
    setStartTime(null);
    setEndTime(null);
  };

  const handleDataChange = (_, value) => {
    setData(value);
  };

  const handleStartChange = (date, _) => {
    setStartTime(date);
  }

  const handleEndChange = (date, _) => {
    setEndTime(date)
  }

  const clickHandler = async (_) => {
    try {
      const cmd = sanitize({command: command, data: data, start: startTime, end: endTime});
      await sendCommand(vins, cmd, token);
      if (vins.length === 1) {
        setMessage(`Sent command to ${vins[0]}`);
      } else {
        setMessage(`Sent command to ${vins.length} cars`);
      }
    } catch (error) {
      setMessage(error.message);
      logger.error(error.stack);
    }
  };

  const getParameters = (cmd) => {
    for (let i = 0, len = commands.length; i < len; i += 1) {
      const item = commands[i];
      if (item.value === cmd) {
        if (!item.params) {
          break;
        }
        return item.params;
      }
    }
    return null;
  };

  useEffect(() => {
    if (!commands || commands.length === 0) return;
    selectCommand(commands[0].value);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className={clsx(classes.paper)} style={{marginTop: 20}}>
      <FormControl
        className={classes.formControl}
        variant="outlined"
        size="small"
      >
        <InputLabel htmlFor="send-command" className={classes.whiteBackground}>
          Command
        </InputLabel>
        <Select
          native
          value={command}
          variant="outlined"
          inputProps={{
            name: "send-command",
            id: "send-command",
          }}
          onChange={changeCommandHandler}
        >
          {commands.map((item, index) => (
            <option key={index} value={item.value}>
              {item.label}
            </option>
          ))}
        </Select>
      </FormControl>
      <Parameters
        params={parameters}
        data={data}
        handleDataChange={handleDataChange}
        startDate={startTime}
        handleStartChange={handleStartChange}
        endDate={endTime}
        handleEndChange={handleEndChange}
      />
      <Button
        type="submit"
        aria-label="send command"
        disabled={busy || vins.length === 0}
        fullWidth
        variant="contained"
        color="primary"
        className={classes.submit}
        onClick={clickHandler}
      >
        {busy ? "Sending..." : "Send"}
      </Button>
    </div>
  );
};

SendCommand.propTypes = {
  vins: PropTypes.array.isRequired,
};

export default SendCommand;
