import { router } from '@inertiajs/react';
import Swal from 'sweetalert2';

/**
 * Hook personalizado para manejar las acciones CRUD de CUPS
 */
export const useContratoHandlers = () => {

  const handleUpdate = async (
    rowId: string,
    dataToUpdate: any,
    onSuccess?: () => void
  ) => {
    if (!dataToUpdate) {
      Swal.fire({
        title: 'Error',
        text: 'No hay datos para actualizar',
        icon: 'error',
        timer: 2000,
        showConfirmButton: false,
      });
      return;
    }

    const cupsId = rowId.split('-')[1];

    try {
      Swal.fire({
        title: 'Actualizando...',
        text: 'Por favor espere',
        allowOutsideClick: false,
        showConfirmButton: false,
        willOpen: () => {
          Swal.showLoading();
        }
      });

      await router.put(
        route('propuesta-comercial-cups.actualizar', cupsId),
        {
          FecActCUPs: dataToUpdate.FecActCUPs,
          FecVenCUPs: dataToUpdate.FecVenCUPs,
          EstConCups: dataToUpdate.EstConCups,
          comercializadora: dataToUpdate.comercializadora,
          producto: dataToUpdate.producto,
          anexo: dataToUpdate.anexo,
          Id_Tarifa_Automatica: dataToUpdate.Id_Tarifa_Automatica,
          nombretarifa: dataToUpdate.nombretarifa,
          productCode: dataToUpdate.productCode,
          version: dataToUpdate.version,
          GDO: dataToUpdate.GDO,
          Permanencia: dataToUpdate.Permanencia,
          CambioTitular: dataToUpdate.CambioTitular,
          CambioPotencia: dataToUpdate.CambioPotencia,
        },
        {
          preserveState: true,
          preserveScroll: true,
          onSuccess: () => {
            if (onSuccess) onSuccess();

            Swal.fire({
              title: 'Actualizado',
              text: 'Los datos han sido actualizados correctamente',
              icon: 'success',
              timer: 2000,
              showConfirmButton: false,
            });
          },
          onError: (errors) => {
            console.error('Error actualizando CUPS:', errors);
            Swal.fire({
              title: 'Error',
              text: 'Error actualizando los datos del CUPS',
              icon: 'error',
              timer: 3000,
              showConfirmButton: false,
            });
          }
        }
      );
    } catch (error) {
      console.error('Error en la actualización:', error);
      Swal.fire({
        title: 'Error',
        text: 'Ocurrió un error inesperado',
        icon: 'error',
        timer: 3000,
        showConfirmButton: false,
      });
    }
  };

  const handleDelete = async (rowId: string) => {
    const cupsId = rowId.split('-')[1];

    const result = await Swal.fire({
      title: '¿Estás seguro?',
      text: 'Esta acción eliminará permanentemente el CUPS. No se puede deshacer.',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Sí, eliminar',
      cancelButtonText: 'Cancelar'
    });

    if (result.isConfirmed) {
      try {
        Swal.fire({
          title: 'Eliminando...',
          text: 'Por favor espere',
          allowOutsideClick: false,
          showConfirmButton: false,
          willOpen: () => Swal.showLoading()
        });

        await router.delete(
          route('propuesta-comercial-cups.eliminar', cupsId),
          {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {
              Swal.fire({
                title: 'Eliminado',
                text: 'El CUPS ha sido eliminado correctamente',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
              });
            },
            onError: (errors) => {
              console.error('Error eliminando CUPS:', errors);
              Swal.fire({
                title: 'Error',
                text: 'Error al eliminar el CUPS',
                icon: 'error',
                timer: 3000,
                showConfirmButton: false
              });
            }
          }
        );
      } catch (error) {
        console.error('Error en la eliminación:', error);
        Swal.fire({
          title: 'Error',
          text: 'Ocurrió un error inesperado',
          icon: 'error',
          timer: 3000,
          showConfirmButton: false
        });
      }
    }
  };

  return {
    handleUpdate,
    handleDelete
  };
};

