import { useCallback } from 'react';
import { router } from '@inertiajs/react';
import { useLoading } from '../../../../../LoadingContext';
// Use ESM import for SweetAlert2 so bundlers (Vite) include it correctly
import Swal from 'sweetalert2';

/**
 * Hook reutilizable que ejecuta la ruta nombrada `anexo-producto.generate-anexos`
 * enviando el parámetro `propuestaId` mediante Inertia y mostrando el spinner
 * global (LoadingContext) mientras se procesa.
 *
 * Uso:
 * const generar = useGenerarCondicionesEconomicas();
 * generar(propuestaId);
 */
const useGenerarContratosCondicionesGeneralesPDF = () => {
  const { showLoading, hideLoading } = useLoading();

  const generar = useCallback((propuestaId?: string | number, comercial?: string, canal?: string) => {
    if (!propuestaId) return;

    // Build the route using the global `route()` helper if available, otherwise fallback
    let target: string;
    try {
      // call route(...) as in other components
      // @ts-ignore
      target = route('anexo-producto.generate-contratos-generales', propuestaId);
    } catch (e) {
      target = `/generate-contratos-generales/${encodeURIComponent(String(propuestaId))}`;
    }

    showLoading();

    // Use Inertia's router to visit the URL so the request is performed with Inertia
    router.get(target, { comercial, canal }, {
      preserveScroll: true,
      onFinish: () => {
        hideLoading();
      },
      onSuccess: (page: any) => {
        // Optionally show flash message similar to other flows
        try {
          const flash: any = (page as any).props?.flash || {};
          const flashMessage = flash?.message || flash?.error;
          // If there's a flash message, show it. Use flash.type when present; fallback to success/info/error.
          if (flashMessage) {
            const icon = flash.type || (flash.error ? 'error' : (flash.success ? 'success' : 'info'));
            Swal.fire({ title: flashMessage, icon, timer: 1500, showConfirmButton: false });
          }
        } catch (err) {
          // ignore
          console.error('Error showing flash message:', err);
        }
      },
      onError: () => {
        try {
          Swal.fire({ title: 'Error al generar anexos', icon: 'error', timer: 1500, showConfirmButton: false });
        } catch (err) {
          // ignore
          console.log('Error showing error flash message:', err);
        }
      }
    });
  }, [showLoading, hideLoading]);

  return generar;
};

export default useGenerarContratosCondicionesGeneralesPDF;
