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

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

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

  const campaign = await prisma.broadcastCampaign.findFirst({
    where: { id: campaignId, tenantId: session.tenantId },
    include: { channel: true, template: true, segment: true, recipients: { include: { contact: true } } }
  });
  if (!campaign) {
    redirect("/campaigns?error=campaign_not_found");
  }

  return (
    <ShellPage
      shell="admin"
      title="Campaign Detail"
      description="Ringkasan total sent, delivered, read, failed, dan breakdown delivery."
    >
      <div className="grid gap-6 xl:grid-cols-2">
        <SectionCard title="Campaign info">
          <p className="text-sm text-on-surface-variant">
            <strong>Nama:</strong> {campaign.name}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Template:</strong> {campaign.template.name}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Channel:</strong> {campaign.channel.channelName}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Audience:</strong> {campaign.audienceType}
          </p>
          <p className="text-sm text-on-surface-variant">
            <strong>Segment:</strong> {campaign.segment ? campaign.segment.name : "-"}
          </p>
        </SectionCard>
        <SectionCard title="Delivery summary">
          <p className="text-sm text-on-surface-variant">
            Total recipients: <strong>{campaign.totalRecipients}</strong>
          </p>
          <p className="text-sm text-on-surface-variant">
            Sent: <strong>{campaign.totalSent}</strong>
          </p>
          <p className="text-sm text-on-surface-variant">
            Delivered: <strong>{campaign.totalDelivered}</strong>
          </p>
          <p className="text-sm text-on-surface-variant">
            Failed: <strong>{campaign.totalFailed}</strong>
          </p>
          <p className="text-sm text-on-surface-variant">
            Read: <strong>{campaign.totalRead}</strong>
          </p>
          <Link href={`/campaigns/${campaign.id}/recipients`} className="mt-4 inline-block text-brand">
            Lihat recipients
          </Link>
        </SectionCard>
      </div>
    </ShellPage>
  );
}
