import { useState } from 'react';
import { router } from '@inertiajs/react';
import { route } from 'ziggy-js';

export const useToggleHandler = (toggleRoute, onSuccessCallback) => {
  const [isToggling, setIsToggling] = useState(false);

  const handleToggle = (id, currentStatus) => {
    const newStatus = currentStatus === '1' ? '0' : '1';

    onSuccessCallback(id, newStatus);

    setIsToggling(true);

    
    router.post(
      route(toggleRoute),
      { id, status: newStatus },
      {
        preserveScroll: true,
        preserveState: true,
        replace: true,
        onError: (errors) => {
          console.error('Toggle failed:', errors);
          onSuccessCallback(id, currentStatus);
        },
        onFinish: () => setIsToggling(false),
      }
    );
  };

  return { handleToggle, isToggling };
};
