import { forwardRef, useImperativeHandle, useState } from "react";
import {
  TextField,
  FormControlLabel,
  Checkbox,
} from "@material-ui/core";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TaskRunner from "../../../utils/taskRunner";
import vehiclesAPI from "../../../services/vehiclesAPI";
import smsAPI from "../../../services/smsAPI";
import { SMS } from "../../Contexts/SMSContext";

export default forwardRef(({
  ids,
  idCSV,
}, ref) => {
  const [shouldAwait, setShouldAwait] = useState(false);
  const [smsMessage, setSmsMessage] = useState("");
  const { setMessage } = useStatusContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();

  useImperativeHandle(ref, () => ({
    async submit() {
      return new Promise((resolve) => {
        const taskRunner = new TaskRunner(30, ids.length);

        ids.forEach((vin) => {
          taskRunner.push(async () => {

            const { iccid } = await vehiclesAPI.getVehicle(vin, token);
            if (!iccid) {
              throw new Error(`Missing ICC ID for ${vin}`);
            }

            const sms = new SMS(smsMessage, iccid, shouldAwait);
            const result = await smsAPI.send(sms, token);
            if (result.error) {
              throw new Error(result.message);
            }

            return vin
          })
            .then((vin) => setMessage(`Sent message to ${vin}`))
            .catch((error) => setMessage(`Failed to send SMS: ${error}`));
        });

        taskRunner.onComplete()
          .then((responses) => {
            setMessage(`Sent ${ids.length} SMS messages`);
            resolve(responses);
          });
      });
    },
  }));

  return (
    <div>
      <p>
        You are about to send SMS to the following vins: {idCSV}.
      </p>
      <TextField
        fullWidth
        label="Message"
        variant="filled"
        onChange={(event) => setSmsMessage(event.target.value)}
      />
      <FormControlLabel
        label="Await"
        control={<Checkbox
          checked={shouldAwait}
          onChange={() => setShouldAwait(shouldAwait => !shouldAwait)}
        />}
      />
    </div>
  );
});