import { ChatMessage } from "@/types/chat.types";

export type MessageGroup = {
  key: string;
  userId: string;
  messages: ChatMessage[];
  isOwn: boolean;
};

export type TimelineItem =
  | { type: "day-separator"; key: string; label: string }
  | { type: "message-group"; key: string; group: MessageGroup };

function startOfDay(date: Date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

function getDayKey(date: Date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function isSameDay(left: Date, right: Date) {
  return (
    left.getFullYear() === right.getFullYear() &&
    left.getMonth() === right.getMonth() &&
    left.getDate() === right.getDate()
  );
}

export function formatDayLabel(date: Date, now: Date) {
  const day = startOfDay(date);
  const today = startOfDay(now);

  if (isSameDay(day, today)) {
    return "Aujourd'hui";
  }

  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);

  if (isSameDay(day, yesterday)) {
    return "Hier";
  }

  return new Intl.DateTimeFormat("fr-FR", {
    day: "numeric",
    month: "long",
    year: "numeric",
  }).format(date);
}

export function buildTimelineItems(groups: MessageGroup[], now: Date) {
  const items: TimelineItem[] = [];
  let previousDayKey: string | null = null;

  for (const group of groups) {
    const firstMessage = group.messages[0];
    if (!firstMessage) {
      continue;
    }

    const messageDate = new Date(firstMessage.createdAt);
    const dayKey = getDayKey(messageDate);

    if (previousDayKey !== dayKey) {
      items.push({
        type: "day-separator",
        key: `day-${dayKey}`,
        label: formatDayLabel(messageDate, now),
      });
      previousDayKey = dayKey;
    }

    items.push({
      type: "message-group",
      key: `group-${group.key}`,
      group,
    });
  }

  return items;
}
