import Link from "next/link";

import { PlaceholderActions, ShellPage } from "@/components/page-templates";
import { TablePlaceholder } from "@/components/placeholders";
import { dispatchCampaign, deleteCampaign } from "@/lib/admin-crud";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export default async function CampaignsPage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string }>; 
}) {
  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const session = await getSession();
  const campaigns = session
    ? await prisma.broadcastCampaign.findMany({
        where: { tenantId: session.tenantId },
        include: { channel: true },
        orderBy: { createdAt: "desc" }
      })
    : [];
  const error = params.error;
  const infoMessage =
    error === "campaign_not_found" ? "Campaign tidak ditemukan." : error === "missing_fields" ? "Lengkapi data campaign." : null;
  const campaignErrorMessage =
    error === "no_recipients" ? "Campaign tidak punya recipient (audience kosong)." : error === "campaign_not_ready" ? "Campaign tidak bisa dikirim dalam status ini." : null;

  return (
    <ShellPage
      shell="admin"
      title="Campaigns"
      description="List campaign broadcast, ringkasan status, dan akses ke flow pembuatan campaign."
      actions={<PlaceholderActions primaryHref="/campaigns/new" primaryLabel="Create campaign" />}
    >
      {infoMessage ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{infoMessage}</p> : null}
      <TablePlaceholder
        title="Campaign list"
        columns={["Campaign", "Channel", "Audience", "Status", "Scheduled", "Actions"]}
        rows={campaigns.map((campaign) => [
          campaign.name,
          campaign.channel.channelName,
          campaign.audienceType,
          campaign.status,
          campaign.scheduledAt ? new Date(campaign.scheduledAt).toLocaleDateString() : "Not scheduled",
          <div key={campaign.id} className="flex flex-wrap gap-2">
            <Link href={`/campaigns/${campaign.id}`} className="text-brand hover:underline">
              Detail
            </Link>
            <Link href={`/campaigns/${campaign.id}/recipients`} className="text-brand hover:underline">
              Recipients
            </Link>
            <form action={dispatchCampaign} className="inline">
              <input type="hidden" name="campaignId" value={campaign.id} />
              <button type="submit" className="text-success hover:underline">
                Dispatch
              </button>
            </form>
            <form action={deleteCampaign} className="inline">
              <input type="hidden" name="campaignId" value={campaign.id} />
              <button type="submit" className="text-danger hover:underline">
                Delete
              </button>
            </form>
          </div>
        ])}
      />
      {campaignErrorMessage ? <p className="mt-4 rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{campaignErrorMessage}</p> : null}
    </ShellPage>
  );
}
