import type { ChatMessage } from "@/components/chat/ChatMessageCard";

export type MessageGroup =
  | { type: "date"; label: string; key: string }
  | { type: "message"; message: ChatMessage; key: string };

function normalizeDateInput(isoOrTime?: string | null): string {
  if (isoOrTime == null || String(isoOrTime).trim() === "") {
    return new Date().toISOString();
  }
  return String(isoOrTime);
}

function formatDateLabel(isoOrTime?: string | null): string {
  const raw = normalizeDateInput(isoOrTime);
  const d = new Date(raw);
  if (!Number.isNaN(d.getTime())) {
    const today = new Date();
    const yesterday = new Date();
    yesterday.setDate(today.getDate() - 1);
    if (d.toDateString() === today.toDateString()) return "امروز";
    if (d.toDateString() === yesterday.toDateString()) return "دیروز";
    return d.toLocaleDateString("fa-IR", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  }
  const fallback = raw.split(" ")[0];
  return fallback || "امروز";
}

function dayKey(isoOrTime?: string | null): string {
  const raw = normalizeDateInput(isoOrTime);
  const d = new Date(raw);
  if (!Number.isNaN(d.getTime())) {
    return d.toDateString();
  }
  return raw.split(" ")[0] || "unknown-day";
}

export function groupMessagesByDate(messages: ChatMessage[]): MessageGroup[] {
  const groups: MessageGroup[] = [];
  let lastDay = "";

  messages.forEach((msg, i) => {
    if (!msg) return;

    const dk = dayKey(msg.createdAt);
    if (dk !== lastDay) {
      lastDay = dk;
      groups.push({
        type: "date",
        label: formatDateLabel(msg.createdAt),
        key: `date-${dk}`,
      });
    }
    groups.push({
      type: "message",
      message: msg,
      key: msg._id || `m-${i}`,
    });
  });

  return groups;
}
