import { useEffect, useState } from "react";
import TransformModal from "../TransformModal";
import DropDownButton from "../Controls/DropDownButton";
import { useUserContext } from "../Contexts/UserContext";
import { useStatusContext } from "../Contexts/StatusContext";
import useAddTags from "./useAddTags";
import useUpdateConfig from "./useUpdateConfig";

const transformArrayToCSV = (arr) => arr.join(", ");

export default function BulkActions({
  vins = [],
}) {
  const [vinCSV, setVinCSV] = useState(transformArrayToCSV(vins));
  const [active, setActive] = useState(null);
  const actions = [
    {
      name: "Update Configs",
      disabled: vins.length === 0,
      trigger: () => setActive("updateConfig"),
    },
    {
      name: "Add Tags",
      disabled: vins.length === 0,
      trigger: () => setActive("addTags"),
    },
  ];

  const updateConfig = useUpdateConfig();
  const addTags = useAddTags();

  const { setMessage } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  const handleUpdateConfig = () => {
    updateConfig.submit(vins, token)
      .then(() => {
        setMessage(`${vins.length} vehicles updated.`);
      })
      .catch((error) => {
        setMessage(error.message);
      });
  }

  const handleAddTags = () => {
    addTags.submit(vins, token)
      .then(() => setMessage(`Added ${addTags.data.tags.value.length} tags to ${vins.length} vehicles.`))
      .catch((error) => setMessage(error.message));
  }

  const handleClose = () => setActive(null);

  useEffect(() => {
    setVinCSV(transformArrayToCSV(vins));
  }, [vins]);

  return (
    <>
      <DropDownButton actions={actions} payload={[vins]} />
      <TransformModal
        title="Update Config"
        body={`You are updating the config for the following VINs: ${vinCSV}.`}
        close={handleClose}
        open={active === "updateConfig"}
        data={updateConfig.data}
        setData={updateConfig.setData}
        submit={handleUpdateConfig}
      />
      <TransformModal
        title="Add Tags"
        body={`You are adding tags for the following VINs: ${vinCSV}.`}
        close={handleClose}
        open={active === "addTags"}
        data={addTags.data}
        setData={addTags.setData}
        submit={handleAddTags}
      />
    </>
  );
}
