type DeliveryRow = {
  id: string;
  channel: "IN_APP" | "PUSH" | "EMAIL" | "SYSTEM" | "SMS" | "VIBER" | "WHATSAPP";
  status: "QUEUED" | "SENT" | "DELIVERED" | "FAILED" | "SKIPPED";
  recipient: string;
  provider: string | null;
  providerMessageId: string | null;
  errorMessage: string | null;
  queuedAt: Date | string;
  sentAt: Date | string | null;
  notification: {
    title: string;
    audience: "ADMIN" | "CLIENT" | "COMPANY";
    company?: { name: string } | null;
    clientAccount?: { email: string; name: string } | null;
    user?: { email: string; name: string | null } | null;
  };
};

function formatDate(value: Date | string | null) {
  if (!value) {
    return "Nije poslato";
  }

  return new Intl.DateTimeFormat("sr-Latn-RS", {
    day: "2-digit",
    month: "long",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(value));
}

export function NotificationDeliveryFeed({ items }: { items: DeliveryRow[] }) {
  return (
    <section className="surface rounded-[2rem] p-6">
      <p className="eyebrow">Isporuka kanala</p>
      <div className="mt-4 divide-y divide-border overflow-hidden rounded-[1.6rem] border border-border bg-white/75">
        {items.map((item) => (
          <article key={item.id} className="grid gap-4 px-5 py-4 xl:grid-cols-[minmax(0,1fr)_260px]">
            <div>
              <p className="font-semibold text-foreground">{item.notification.title}</p>
              <p className="mt-2 text-sm text-muted-foreground">
                {item.recipient} · {item.channel} · {item.status}
              </p>
              <p className="mt-2 text-xs uppercase tracking-[0.14em] text-muted-foreground">
                {item.notification.company?.name ||
                  item.notification.clientAccount?.email ||
                  item.notification.user?.email ||
                  "Sistem"}
              </p>
              {item.errorMessage ? (
                <p className="mt-3 text-sm text-[color:var(--color-danger)]">{item.errorMessage}</p>
              ) : null}
            </div>
            <div className="text-sm text-muted-foreground">
              <p>Stavljeno u red: {formatDate(item.queuedAt)}</p>
              <p className="mt-2">Poslato: {formatDate(item.sentAt)}</p>
              <p className="mt-2">Provider: {item.provider || "N/A"}</p>
              <p className="mt-2 break-all">Poruka ID: {item.providerMessageId || "N/A"}</p>
            </div>
          </article>
        ))}
        {!items.length ? (
          <div className="px-5 py-4 text-sm text-muted-foreground">
            Još nema delivery zapisa. Kada email, push ili webhook kanali krenu da šalju poruke, statusi će se prikazivati ovde.
          </div>
        ) : null}
      </div>
    </section>
  );
}
