import Link from "next/link";
import { redirect } from "next/navigation";

import { ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";
import { SectionCard } from "@/components/ui";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

function summarizeRules(value: string | null) {
  if (!value) {
    return "-";
  }

  try {
    const parsed = JSON.parse(value);
    return parsed.description ? String(parsed.description) : JSON.stringify(parsed);
  } catch {
    return value;
  }
}

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

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

export default async function SegmentDetailPage({ params }: { params: Promise<{ segmentId: string }> }) {
  const { segmentId } = await params;
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const segment = await prisma.contactSegment.findFirst({
    where: { id: segmentId, tenantId: session.tenantId },
    include: {
      _count: {
        select: { members: true }
      },
      members: {
        include: { contact: true },
        orderBy: { createdAt: "desc" },
        take: 20
      },
      campaigns: {
        select: { id: true, name: true, status: true, updatedAt: true },
        orderBy: { updatedAt: "desc" }
      }
    }
  });

  if (!segment) {
    redirect("/contacts/segments?error=segment_not_found");
  }

  return (
    <ShellPage
      shell="admin"
      title="Segment Detail"
      description="Metadata segment, preview members, dan campaign yang memakai segment ini."
      actions={<Link href="/contacts/segments">Back to segments</Link>}
    >
      <div className="grid gap-6 xl:grid-cols-2">
        <SectionCard title="Segment metadata">
          <p className="text-sm text-on-surface-variant">Nama: {segment.name}</p>
          <p className="text-sm text-on-surface-variant">Rule: {summarizeRules(segment.description ?? segment.rulesJson)}</p>
          <p className="text-sm text-on-surface-variant">Members: {segment._count.members}</p>
          <p className="text-sm text-on-surface-variant">Updated: {formatDate(segment.updatedAt)}</p>
        </SectionCard>
        <SectionCard title="Campaign usage">
          {segment.campaigns.length === 0 ? (
            <p className="text-sm text-on-surface-variant">Tidak ada campaign yang memakai segment ini.</p>
          ) : (
            <ul className="space-y-2">
              {segment.campaigns.map((campaign) => (
                <li key={campaign.id} className="rounded-xl border border-line bg-surface-container p-3">
                  <Link href={`/campaigns/${campaign.id}`} className="text-brand hover:underline">
                    {campaign.name}
                  </Link>
                  <p className="text-xs text-outline">Status: {campaign.status} • {formatDate(campaign.updatedAt)}</p>
                </li>
              ))}
            </ul>
          )}
        </SectionCard>
      </div>
      {segment.members.length > 0 ? (
        <TablePlaceholder
          title="Member preview"
          columns={["Contact", "Phone", "Added at"]}
          rows={segment.members.map((member) => [
            member.contact.fullName,
            member.contact.phoneNumber,
            formatDate(member.createdAt)
          ])}
        />
      ) : null}
    </ShellPage>
  );
}
