import { useEffect, useState, useRef, Suspense, lazy } from "react";
import { hasRole, Permissions } from "../../utils/roles";
import DropDownButton from "../Controls/DropDownButton";
import { useUserContext } from "../Contexts/UserContext";
import { Modal } from "./Modal";
import truncateCSV from "../../utils/truncateCSV";

// Code-splitting individual actions
// https://react.dev/reference/react/lazy
const AddTags = lazy(() => import("./actions/AddTags"));
const Cancel = lazy(() => import("./actions/Cancel"));
const Diagnostic = lazy(() => import("./actions/Diagnostic"));
const Redeploy = lazy(() => import("./actions/Redeploy"));
const RemoteCommand = lazy(() => import("./actions/RemoteCommand"));
const SendSMS = lazy(() => import("./actions/SendSMS"));
const UpdateConfig = lazy(() => import("./actions/UpdateConfig"));
const UpdateFleetVehicles = lazy(() => import("./actions/UpdateFleetVehicles"));
const UpdateFlashpackNumbers = lazy(() => import("./actions/UpdateFlashpackNumbers"));

export default function BulkActions({
  ids = [],
  actions = [],
  callback = (active, ids, context) => { }, // context is raised from the action itself
}) {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("Action");
  const [active, setActive] = useState(null);
  const [embedded, setEmbedded] = useState(false); // If the "submit" is embedded in the linked component
  const activeRef = useRef();
  const { groups, providers } = useUserContext();

  const filteredActions = [
    {
      id: "addTags",
      name: "Add Tags",
      disabled: false,
      trigger: () => setActive("addTags"),
    },
    {
      id: "cancel",
      name: "Cancel Updates",
      disabled: false,
      trigger: () => setActive("cancel"),
    },
    {
      id: "diagnostic",
      name: "Send Diagnostic",
      disabled: false, //!hasRole(groups, Permissions.CarDiagnostic, providers),
      trigger: () => setActive("diagnostic"),
    },
    {
      id: "redeploy",
      name: "Redploy Updates",
      disabled: false,
      trigger: () => setActive("redeploy"),
    },
    {
      id: "remoteCommand",
      name: "Send Command",
      disabled: false,
      trigger: () => setActive("remoteCommand"),
      embedded: true,
    },
    {
      id: "sms",
      name: "Send SMS",
      disabled: !hasRole(groups, Permissions.FiskerCreate, providers),
      trigger: () => setActive("sms"),
    },
    {
      id: "updateConfig",
      name: "Update Config",
      disabled: false,
      trigger: () => setActive("updateConfig"),
    },
    {
      id: "updateFleetVehicles",
      name: "Move Vehicles",
      disabled: false,
      trigger: () => setActive("updateFleetVehicles"),
    },
    {
      id: "updateFlashpackNumbers",
      name: "Update Flashpack Numbers",
      disabled: false,
      trigger: () => setActive("updateFlashpackNumbers")
    }
  ].filter((action) => actions.includes(action.id));

  const payload = {
    ids,
    idCSV: (ids && ids.length > 0) ? truncateCSV(ids, 10) : "N/A",
    ref: activeRef
  };

  const handleClose = () => {
    setOpen(false);
  }

  const handleSubmit = () => {
    if (activeRef.current.submit) {
      activeRef.current.submit().then((error) => callback(active, ids, error));
    }
    handleClose();
  }

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

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

  return (
    <>
      <DropDownButton actions={filteredActions} onClick={() => setOpen(true)} />
      <Modal
        title={title}
        open={open}
        close={handleClose}
        submit={handleSubmit}
        hideSubmit={embedded}
      >
        <Suspense fallback={<div>Loading...</div>}>
          <section>
            {active === "addTags" && <AddTags {...payload} />}
            {active === "cancel" && <Cancel {...payload} />}
            {active === "diagnostic" && <Diagnostic {...payload} />}
            {active === "redeploy" && <Redeploy {...payload} />}
            {active === "remoteCommand" && <RemoteCommand {...payload} />}
            {active === "sms" && <SendSMS {...payload} />}
            {active === "updateConfig" && <UpdateConfig {...payload} />}
            {active === "updateFleetVehicles" && <UpdateFleetVehicles {...payload} />}
            {active === "updateFlashpackNumbers" && <UpdateFlashpackNumbers {...payload} />}
          </section>
        </Suspense>
      </Modal>
    </>
  )
}
