import {
  addDays,
  endOfMonth,
  endOfWeek,
  format,
  isSameDay,
  isToday,
  parseISO,
  startOfMonth,
  startOfWeek
} from "date-fns";

export const colorOptions = ["slate", "rose", "amber", "emerald", "blue"] as const;
const apiBaseUrl = (import.meta.env.VITE_API_URL || "http://localhost:48080").replace(/\/+$/, "");

export const colorMap: Record<string, { bg: string; text: string; line: string }> = {
  slate: { bg: "rgba(103, 112, 130, 0.12)", text: "#5d6777", line: "rgba(103, 112, 130, 0.2)" },
  rose: { bg: "rgba(229, 125, 125, 0.14)", text: "#c95c61", line: "rgba(229, 125, 125, 0.22)" },
  amber: { bg: "rgba(214, 161, 85, 0.16)", text: "#a86e1f", line: "rgba(214, 161, 85, 0.24)" },
  emerald: { bg: "rgba(111, 143, 116, 0.16)", text: "#4a7550", line: "rgba(111, 143, 116, 0.24)" },
  blue: { bg: "rgba(111, 150, 211, 0.16)", text: "#4d6ea8", line: "rgba(111, 150, 211, 0.22)" }
};

export function getColorStyle(name: string) {
  return colorMap[name] ?? colorMap.slate;
}

export function formatStamp(value?: string) {
  if (!value) {
    return "No date";
  }
  return format(parseISO(value), "MMM d, HH:mm");
}

export function formatDayLabel(value: Date) {
  return format(value, "EEE d");
}

export function formatPrettyDate(value?: string) {
  if (!value) {
    return "Unscheduled";
  }
  const date = parseISO(value);
  return isToday(date) ? `Today, ${format(date, "HH:mm")}` : format(date, "MMM d, HH:mm");
}

export function daysForMonth(base: Date) {
  const start = startOfWeek(startOfMonth(base), { weekStartsOn: 1 });
  const end = endOfWeek(endOfMonth(base), { weekStartsOn: 1 });
  const days: Date[] = [];
  for (let cursor = start; cursor <= end; cursor = addDays(cursor, 1)) {
    days.push(cursor);
  }
  return days;
}

export function sameDay(value: string | undefined, day: Date) {
  return value ? isSameDay(parseISO(value), day) : false;
}

export function resolveAttachmentHref(value?: string) {
  if (!value) {
    return "#";
  }
  if (value.startsWith("data:") || value.startsWith("http://") || value.startsWith("https://")) {
    return value;
  }
  if (value.startsWith("/")) {
    return `${apiBaseUrl}${value}`;
  }
  return `${apiBaseUrl}/${value}`;
}
