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

import { useVehicleContext } from "../../Contexts/VehicleContext";
import commands from "../../../services/commands";
import useStyles from "../../useStyles";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";

const SendCommand = ({ vins }) => {
  const classes = useStyles();
  const { sendCommand, busy } = useVehicleContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const NoParameters = {
    value: "",
    label: "None",
  };
  const { setMessage } = useStatusContext();
  const [command, setCommand] = useState("");
  const [parameters, setParameters] = useState([NoParameters]);
  const [parameter, setParameter] = useState("");
  const changeCommandHandler = (e) => {
    selectCommand(e.target.value);
  };

  const selectCommand = (cmd) => {
    const params = getParameters(cmd);
    setCommand(cmd);
    setParameters(params);
    setParameter(params[0].value);
  };

  const changeParametersHandler = (e) => {
    setParameter(e.target.value);
  };

  const clickHandler = async (e) => {
    try {
      await sendCommand(vins, command, parameter, token);
      if (vins.length === 1) {
        setMessage(`Sent command to ${vins[0]}`);
      } else {
        setMessage(`Sent command to ${vins.length} cars`);
      }
    } catch (e) {
      setMessage(e.message);
    }
  };

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

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

  return (
    <div className={classes.form}>
      <FormControl className={classes.formControlInline} variant="outlined">
        <InputLabel htmlFor="send-command" style={{ backgroundColor: "White" }}>
          Command
        </InputLabel>
        <Select
          native
          value={command}
          variant="outlined"
          inputProps={{
            name: "send-command",
            id: "send-command",
          }}
          onChange={changeCommandHandler}
        >
          {commands.map((item) => (
            <option key={item.value} value={item.value}>
              {item.label}
            </option>
          ))}
        </Select>
      </FormControl>
      <FormControl className={classes.formControlInline} variant="outlined">
        <InputLabel
          htmlFor="send-parameter"
          style={{ backgroundColor: "White" }}
        >
          Parameter
        </InputLabel>
        <Select
          native
          value={parameter}
          variant="outlined"
          inputProps={{
            name: "send-parameter",
            id: "send-parameter",
          }}
          onChange={changeParametersHandler}
          disabled={parameters.length === 0}
        >
          {parameters.map((item) => (
            <option key={item.value} value={item.value}>
              {item.label}
            </option>
          ))}
        </Select>
      </FormControl>
      <IconButton
        color="primary"
        aria-label="send command"
        component="span"
        onClick={clickHandler}
        disabled={busy || vins.length === 0}
      >
        <SendIcon fontSize="large" />
      </IconButton>
    </div>
  );
};

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

export default SendCommand;
