import { PlaceholderActions, ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import Link from "next/link";

function formatDate(date: Date | null | undefined) {
  if (!date) {
    return "-";
  }

  return new Intl.DateTimeFormat("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric"
  }).format(date);
}

function summarizeRules(raw: string | null) {
  if (!raw) {
    return "No rules defined";
  }
  try {
    const parsed = JSON.parse(raw) as { description?: string };
    if (parsed.description) {
      return parsed.description;
    }
  } catch {
    return raw;
  }

  return raw;
}

export default async function SegmentsPage() {
  const session = await getSession();
  if (!session) {
    return (
      <ShellPage shell="admin" title="Segments" description="Audience segment untuk kebutuhan broadcast campaign.">
        <p className="rounded-xl border border-line bg-surface-container p-3 text-sm text-on-surface-variant">Silakan login terlebih dahulu.</p>
      </ShellPage>
    );
  }

  const tenantId = session.tenantId;
  const segments = await prisma.contactSegment.findMany({
    where: { tenantId },
    include: {
      _count: {
        select: { members: true }
      }
    },
    orderBy: { updatedAt: "desc" }
  });

  return (
    <ShellPage
      shell="admin"
      title="Segments"
      description="Audience segment untuk kebutuhan broadcast campaign."
      actions={<PlaceholderActions primaryHref="/contacts/segments/new" primaryLabel="Create segment" />}
    >
      <TablePlaceholder
        title="Segments list"
        columns={["Segment", "Rule summary", "Members", "Updated"]}
        rows={segments.map((segment) => [
          <Link key={`${segment.id}-name`} href={`/contacts/segments/${segment.id}`} className="text-brand hover:underline">
            {segment.name}
          </Link>,
          summarizeRules(segment.description ?? segment.rulesJson),
          String(segment._count.members),
          formatDate(segment.updatedAt)
        ])}
      />
    </ShellPage>
  );
}
