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';
import { use } from 'i18next';

/**
 * Hook reutilizable que ejecuta la ruta nombrada `anexo-producto.generate-sepa`
 * enviando el parámetro `propuestaId` mediante Inertia y mostrando el spinner
 * global (LoadingContext) mientras se procesa.
 *
 * Uso:
 * const generar = useGenerarSEPAsPDF();
 * generar(propuestaId);
 */
const useGenerarAnexosCambioPotenciaTitularPDF = () => {
  console.log('useGenerarAnexosCambioPotenciaTitularPDF: Iniciando generación de GenerarAnexosCambioPotenciaTitularPDF');
  const { showLoading, hideLoading } = useLoading();
  const generar = useCallback((propuestaId?: string | number, comercial?: string, canal?: string) => {
    if (!propuestaId) {
      console.warn('useGenerarAnexosCambioPotenciaTitularPDF: propuestaId no proporcionado');
      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-anexos-cambio-potencia-titular', propuestaId);
    } catch (e) {
      target = `/generate-anexos-cambio-potencia-titular/${encodeURIComponent(String(propuestaId))}`;
    }

    showLoading('Generando documentos cambio potencia y titular...');

    // Use Inertia's router to visit the URL so the request is performed with Inertia
    router.get(target, { comercial, canal }, {
      preserveScroll: true,
      onStart: () => {
        console.log('cambio potencia y titular Request iniciado');
      },
      onFinish: () => {
        console.log('cambio potencia y titular Request finalizado');
        hideLoading();
      },
      onSuccess: (page: any) => {
        console.log('cambio potencia y titular Success response:', page);
        // Optionally show flash message similar to other flows
        try {
          const flash: any = (page as any).props?.flash || {};
          // If there's a flash message, show it. Use flash.type when present; fallback to success/info.
          if (flash && flash.message) {
            const icon = flash.type === 'error' ? 'error' : (flash.type === 'warning' ? 'warning' : 'success');
            Swal.fire({
              title: flash.type === 'success' ? '¡Éxito!' : (flash.type === 'warning' ? 'Advertencia' : 'Información'),
              text: flash.message,
              icon,
              confirmButtonText: 'Aceptar'
            });
          } else {
            // Si no hay mensaje flash, mostrar mensaje por defecto
            Swal.fire({
              title: '¡Listo!',
              text: 'Documentos cambio potencia y titular procesados correctamente',
              icon: 'success',
              timer: 2000,
              showConfirmButton: false
            });
          }
        } catch (err) {
          console.error('Error showing flash message:', err);
        }
      },
      onError: (errors: any) => {
        console.error('cambio potencia y titular: Error response:', errors);
        try {
          const errorMessage = typeof errors === 'object' ?
            Object.values(errors).join(', ') :
            'Error al generar documento cambio potencia y titular';

          Swal.fire({
            title: 'Error',
            text: errorMessage,
            icon: 'error',
            confirmButtonText: 'Entendido',
            confirmButtonColor: '#d33'
          });
        } catch (err) {
          console.log('Error showing error flash message:', err);
        }
      }
    });
  }, [showLoading, hideLoading]);

  return generar;
};

export default useGenerarAnexosCambioPotenciaTitularPDF;
