import React, { useState } from "react";
import { useResourcesApi } from "../api";
import DeleteDialog from "./components/DeleteDialog";
import { useToast } from "../../../hooks";

const useResourceDeleteDialog = (resource, setProcessing, onComplete) => {
  const [state, setState] = useState(
    resource ?? { resourceId: null, resourceName: null }
  );
  const [deleteDialogOpen, setOpen] = useState(false);

  const { deleteResource } = useResourcesApi();
  const { success } = useToast();

  const handleDelete = async (resourceId) => {
    setProcessing && setProcessing("delete");
    const response = await deleteResource(resourceId);
    if (response && response.resourceId === state.resourceId) {
      success(`Resource '${state.resourceName}' was successfully deleted.`);
      setProcessing && setProcessing(null);
      setOpen(false);
      onComplete && onComplete(state);
    }
  };

  return {
    component: (
      <DeleteDialog
        title={state.resourceName}
        open={deleteDialogOpen}
        onClose={() => setOpen(false)}
        onConfirm={() => handleDelete(state.resourceId)}
      />
    ),
    handleOpen: (_event, resource) => {
      resource && setState(resource);
      setOpen(true);
    }
  };
};

export default useResourceDeleteDialog;
