import { useEffect, useState, useRef, Suspense, lazy } from "react";
import DropDownButton from "../Controls/DropDownButton";
import { Modal } from "./Modal";

// Code-splitting individual actions
// https://react.dev/reference/react/lazy
const AddTags = lazy(() => import("./actions/AddTags"));
const AddToFleet = lazy(() => import("./actions/AddToFleet"));
const DeleteVehicles = lazy(() => import("./actions/DeleteVehicles"));
const UpdateConfig = lazy(() => import("./actions/UpdateConfig"));

export default function BulkActions({
  vins = [],
  actions = [],
}) {
  const [title, setTitle] = useState("Action");
  const [active, setActive] = useState(null);
  const activeRef = useRef();

  const filteredActions = [
    {
      id: "addTags",
      name: "Add Tags",
      disabled: false,
      trigger: () => setActive("addTags"),
    },
    {
      id: "addToFleet",
      name: "Add To Fleet",
      disabled: false,
      trigger: () => setActive("addToFleet"),
    },
    {
      id: "deleteVehicles",
      name: "Delete",
      disabled: false,
      trigger: () => setActive("deleteVehicles"),
    },
    {
      id: "updateConfig",
      name: "Update Config",
      disabled: false,
      trigger: () => setActive("updateConfig"),
    }
  ].filter((action) => actions.includes(action.id));

  const payload = {
    vins,
    vinCSV: (vins && vins.length > 0) ? vins.join(", ") : "N/A",
    ref: activeRef
  };

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

  const handleSubmit = () => {
    activeRef.current.submit();
    handleClose();
  }

  useEffect(() => {
    setTitle(filteredActions.find((action) => active === action.id)?.name || "Action");
  }, [active, filteredActions]);

  if (!vins || vins.length === 0) return <></>;

  return (
    <>
      <DropDownButton actions={filteredActions} />
      <Modal
        title={title}
        open={!!active}
        close={handleClose}
        submit={handleSubmit}
      >
        <Suspense fallback={<div>Loading...</div>}>
          <section>
            {active === "addTags" && <AddTags {...payload} />}
            {active === "addToFleet" && <AddToFleet {...payload} />}
            {active === "deleteVehicles" && <DeleteVehicles {...payload} />}
            {active === "updateConfig" && <UpdateConfig {...payload} />}
          </section>
        </Suspense>
      </Modal>
    </>
  )
}
