import { useState } from 'react';
import { router } from '@inertiajs/react';

import { route } from 'ziggy-js';

export const useDeleteHandler = (deleteRoute, onSuccessCallback) => {
  const [isDeleting, setIsDeleting] = useState(false);

  const handleDelete = async (id) => {
    setIsDeleting(true);
    try {
      await router.post(route(deleteRoute), { id }, {
        preserveScroll: true,
        onSuccess: () => {
          onSuccessCallback(id);
          setIsDeleting(false);
        },
        onError: (errors) => {
          console.error('Deletion failed:', errors);
          setIsDeleting(false);
        },
      });
    } catch (error) {
      console.error('An unexpected error occurred:', error);
      setIsDeleting(false);
    }
  };

  return { handleDelete, isDeleting };
};