import { format } from "date-fns"
import { es } from "date-fns/locale"
import { getActionCutoff } from "@/lib/reservations/rules"
import { sendEmail } from "@/lib/notifications/email"

export async function sendReservationReminderEmail({
  to,
  userName,
  resourceName,
  locationLabel,
  startAt,
  endAt,
  cancellationDeadlineMinutes,
}: {
  to: string
  userName: string
  resourceName: string
  locationLabel: string
  startAt: string
  endAt: string
  cancellationDeadlineMinutes: number
}) {
  const start = new Date(startAt)
  const end = new Date(endAt)
  const cancelCutoff = getActionCutoff({
    startAt,
    minutesBeforeStart: cancellationDeadlineMinutes,
  })

  const subject = `Recordatorio de reserva: ${resourceName}`
  const startText = format(start, "EEEE d 'de' MMMM, HH:mm", { locale: es })
  const endText = format(end, "HH:mm", { locale: es })
  const cutoffText = format(cancelCutoff, "EEEE d 'de' MMMM, HH:mm", { locale: es })

  const html = `
    <div style="font-family: Arial, sans-serif; color: #303036;">
      <h2 style="margin-bottom: 8px;">Recordatorio de tu reserva</h2>
      <p style="margin-top: 0; margin-bottom: 16px;">Hola ${userName}, tu reserva esta cerca.</p>
      <ul style="padding-left: 18px;">
        <li><strong>Recurso:</strong> ${resourceName}</li>
        <li><strong>Ubicacion:</strong> ${locationLabel}</li>
        <li><strong>Horario:</strong> ${startText} - ${endText}</li>
        <li><strong>Limite para cancelar/editar:</strong> ${cutoffText}</li>
      </ul>
      <p style="margin-top: 16px;">Ingresa a HU Rooms para confirmar, editar o cancelar tu reserva.</p>
    </div>
  `

  const text = [
    `Hola ${userName}, tu reserva esta cerca.`,
    `Recurso: ${resourceName}`,
    `Ubicacion: ${locationLabel}`,
    `Horario: ${startText} - ${endText}`,
    `Limite para cancelar/editar: ${cutoffText}`,
    "Ingresa a HU Rooms para confirmar, editar o cancelar tu reserva.",
  ].join("\n")

  return sendEmail({ to, subject, html, text })
}
