import { router } from "@inertiajs/react";
import Swal from "sweetalert2";
import { promptComercialCanal } from "./Contratos/promptComercialCanal";
import {
    promptCondicionesParticulares,
    RepresentanteLegalOption,
} from "./Contratos/promptCondicionesParticulares";

export const formatToYYYYMMDD = (dateString: string): string => {
    if (!dateString) return '';
    const parts = dateString.split('/');
    if (parts.length === 3) {
        const day = parts[0].padStart(2, '0');
        const month = parts[1].padStart(2, '0');
        const year = parts[2];
        return `${year}-${month}-${day}`;
    }
    return dateString;
};

export interface ArrayWithRecords extends Array<unknown> {}

export const isArrayWithRecords = (variable: unknown): variable is ArrayWithRecords => {
  return Array.isArray(variable) && variable.length > 0;
};

export function saveContratoComercial(
  propuesta: number,
  tipo: number,
  servicioIntegracion: string,
  comercial: string,
  canal: string,
  showLoading: () => void,
  hideLoading: () => void,
  onSuccess?: (msg: string) => void,
  onError?: (msg: string) => void,
  representantesLegales: RepresentanteLegalOption[] = []
) {
  const ensureDatos = async (): Promise<{ comercial: string; canal: string; CodConCli?: string } | null> => {
    if (tipo === 1 || tipo === 2) {
      const valores = await promptCondicionesParticulares(representantesLegales);
      if (!valores) {
        return null;
      }
      return valores;
    }

    return promptComercialCanal({ comercial, canal });
  };

  (async () => {
    const datos = await ensureDatos();
    if (!datos) return;

    try {
      localStorage.setItem('eneon_comercial', datos.comercial);
      localStorage.setItem('eneon_canal', datos.canal);
    } catch (e) {
      // ignorar si localStorage no está disponible
    }

    showLoading();

    const payload: Record<string, string | number> = {
      propuesta_id: propuesta,
      tipoPropuesta: tipo,
      servicio: servicioIntegracion,
      comercial: datos.comercial,
      canal: datos.canal,
    };

    if (datos.CodConCli) {
      payload.CodConCli = datos.CodConCli;
    }

    router.post(
      route("integracion.contratar"),
      payload,
      {
        preserveState: true,
        preserveScroll: true,
        onSuccess: (page) => {
          hideLoading();
          if (
            page.props &&
            page.props.flash &&
            typeof page.props.flash === "object" &&
            "success" in page.props.flash
          ) {
            const msg = (page.props.flash as { success?: string }).success;
            Swal.fire("¡Correcto!", msg, "success");
            if (onSuccess) onSuccess(msg || "");
          }
        },
        onError: (errors) => {
          hideLoading();
          const msg =
            errors.error ||
            "Hubo un problema al registrar el contrato.";
          Swal.fire("¡Error!", msg, "error");
          if (onError) onError(msg);
        },
      }
    );
  })();
}
