import { useState, forwardRef, useImperativeHandle } from "react";
import {
  FormControl,
} from '@material-ui/core';
import SearchSelect from "../../SearchSelect/SearchSelect";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import fleetsAPI from "../../../services/fleetsAPI";

export default forwardRef(({
  ids,
  idCSV,
  fleet,
}, ref) => {
  const { setMessage } = useStatusContext();
  const { token: { idToken: { jwtToken: token } } } = useUserContext();

  const [fromFleet, setFromFleet] = useState(fleet);
  const [toFleet, setToFleet] = useState();

  useImperativeHandle(ref, () => ({
    async submit() {
      const errorTracking = [false, false];

      if (toFleet) {
        await fleetsAPI
          .addFleetVehicles(toFleet, ids, token)
          .then((response) => {
            if (response.error) {
              errorTracking[0] = true;
              setMessage(`${response.error}: ${response.message}`);
            }

            if (response.vins) {
              setMessage(`Added ${response.vins.length} vehicles to ${toFleet}.`);
              return;
            }

            setMessage(`Something unexpected happened while attempting to add vehicles to fleet.`);
          })
          .catch((error) => {
            setMessage(JSON.stringify(error));
            return Promise.reject("Could not add vehicles to fleet.");
          });
      }

      if (fromFleet) {
        await fleetsAPI
          .deleteFleetVehicles(fromFleet, ids, token)
          .then((response) => {
            if (response.error) {
              errorTracking[1] = true;
              setMessage(`${response.error}: ${response.message}`);
            }

            if (response.message === "Deleted") {
              setMessage(`Removed ${ids.length} vehicles from ${fromFleet}.`);
              return;
            }
          })
          .catch((error) => {
            setMessage(JSON.stringify(error));
            return Promise.reject("Could not remove vehicles from fleet.");
          });
      }

      return {
        fromFleet,
        fromVehicles: errorTracking[1] ? [] : ids,
        toFleet,
        toVehicles: errorTracking[0] ? [] : ids,
      };
    },
  }));

  async function searchFleets(search) {
    return fleetsAPI
      .getFleets({
        search,
        limit: 10,
        offset: 0,
        order: `id desc`,
      }, token)
      .then(response => response.data.map(fleet => fleet.name))
      .catch(() => []);
  }

  return (
    <div>
      <p>
        This operation will affect fleet membership for the following VINs: {idCSV}.
      </p>
      <p>
        VINs will be removed from the "From Fleet" and added to the "To Fleet". If you would
        like to only add or only remove the other field can be left blank.
      </p>
      <FormControl variant="filled" fullWidth={true}>
        <SearchSelect
          label="Remove From Fleet"
          value={fromFleet}
          setValue={setFromFleet}
          getData={searchFleets}
          research={true}
        />
      </FormControl>
      <FormControl variant="filled" fullWidth={true}>
        <SearchSelect
          label="Add To Fleet"
          value={toFleet}
          setValue={setToFleet}
          getData={searchFleets}
          research={true}
        />
      </FormControl>
    </div>
  );
});