import { useState, forwardRef, useImperativeHandle } from "react";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import TextInputList from "../../Controls/TextInputList";
import vehiclesAPI from "../../../services/vehiclesAPI";

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

  const [tags, setTags] = useState([]);

  useImperativeHandle(ref, () => ({
    async submit() {
      return vehiclesAPI
        .addTags(ids, tags, token)
        .then((data) => {
          if (data.error) {
            setMessage(`${data.error}: ${data.message}`);
          } else if (data.tags && data.vins) {
            setMessage(`Added ${data.tags.length} tags to ${data.vins.length} vehicles.`);
          } else {
            setMessage(JSON.stringify(data));
          }
        });
    },
  }));

  return (
    <div>
      <p>
        You are adding tags to the following VINs: {idCSV}.
      </p>
      <TextInputList
        label="Tags"
        onChange={setTags}
      />
    </div>
  );
});