import React, { useRef, useState } from "react";
import {
  Button,
  FormControlLabel,
  Checkbox,
  TextField,
} from "@material-ui/core";

import useStyles from "../../useStyles";
import { SMS } from "../../Contexts/SMSContext";

const SendForm = ({ onSend, busy }) => {
  const classes = useStyles();

  const iccidEl = useRef(null);

  const [message, setMessage] = useState(null);
  const [isAwaited, setAwait] = useState(false);

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

    if (onSend) onSend(new SMS(message, iccidEl.current.value, isAwaited));
  };

  const onMessageChange = (event) => {
    setMessage(event.target.value);
  };

  const onAwaitChange = (event) => {
    setAwait(event.target.checked);
  };

  return (
    <div className={classes.paper}>
      <form className={classes.form} noValidate action="{onSubmit}">
        <TextField
          id="iccid"
          name="iccid"
          label="ICCID"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "50",
            minLength: "15",
          }}
          required
          fullWidth
          inputRef={iccidEl}
        />
        <TextField
          id="message"
          name="message"
          label="Message"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "320",
          }}
          required
          fullWidth
          onChange={onMessageChange}
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={isAwaited}
              onChange={onAwaitChange}
              value="isAwaited"
              color="primary"
            />
          }
          label="Await delivery"
        />

        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Sending..." : "Send"}
        </Button>
      </form>
    </div>
  );
};

export default SendForm;
