const DIAS = ["DOM.", "LUN.", "MAR.", "MIÉ.", "JUE.", "VIE.", "SÁB."];

export function defaultFechaEntregaLocal({ days = 3, hour = 20 } = {}) {
  const d = new Date();
  d.setSeconds(0, 0);
  d.setMilliseconds(0);
  d.setDate(d.getDate() + days);
  d.setMinutes(0);
  d.setHours(hour, 0, 0, 0);
  return toDatetimeLocalValue(d);
}

export function toDatetimeLocalValue(date) {
  if (!date || Number.isNaN(date.getTime())) return "";
  const pad = (n) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(
    date.getMinutes()
  )}`;
}

export function parseIsoToDatetimeLocal(iso) {
  if (!iso) return "";
  const s = String(iso).trim();
  const m = s.match(/^(\d{4}-\d{2}-\d{2})[ T](\d{2}):(\d{2})/);
  if (m) {
    return `${m[1]}T${m[2]}:${m[3]}`;
  }
  return toDatetimeLocalValue(new Date(iso));
}

export function datetimeLocalToIso(localValue) {
  return datetimeLocalToServerPayload(localValue);
}

/**
 * Envía fecha/hora tal como la captura el usuario (sin convertir a UTC).
 * Ej. "2026-06-01T18:30" -> "2026-06-01 18:30:00"
 */
export function datetimeLocalToServerPayload(localValue) {
  if (!localValue) return null;
  const match = String(localValue).match(/^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})/);
  if (!match) return null;
  return `${match[1]} ${match[2]}:${match[3]}:00`;
}

export function promisedFechaEntregaIso(orden, { days = 3, hour = 20 } = {}) {
  if (orden?.fecha_entrega) return orden.fecha_entrega;
  if (!orden?.created_at) return null;
  const d = new Date(orden.created_at);
  if (Number.isNaN(d.getTime())) return null;
  d.setSeconds(0, 0);
  d.setMilliseconds(0);
  d.setDate(d.getDate() + days);
  d.setMinutes(0);
  d.setHours(hour, 0, 0, 0);
  return toDatetimeLocalValue(d).replace("T", " ") + ":00";
}

export function formatFechaEntregaDisplay(iso) {
  if (!iso) return "—";
  const s = String(iso).trim();
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/);
  if (m) {
    const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]));
    const pad = (n) => String(n).padStart(2, "0");
    const dia = DIAS[d.getDay()] ?? "";
    return `${dia} ${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(
      d.getMinutes()
    )} Hrs`;
  }
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  const pad = (n) => String(n).padStart(2, "0");
  const dia = DIAS[d.getDay()] ?? "";
  return `${dia} ${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(
    d.getMinutes()
  )} Hrs`;
}

export function formatHorasParaEntrega(horas) {
  const h = Number(horas);
  if (!Number.isFinite(h)) return "—";
  if (h < 0) return `vencida (${Math.abs(h).toFixed(1)} h)`;
  if (h < 1) return `${Math.round(h * 60)} min`;
  return `${h.toFixed(1)} h`;
}
