import { notFound, redirect } from "next/navigation";
import { format } from "date-fns";
import { Megaphone, Users, Send, XCircle, MinusCircle, Coins } from "lucide-react";
import { eq } from "drizzle-orm";
import { db } from "@db/client";
import { customerSegments } from "@db/schema";
import { getDashboardUser } from "@/lib/view-as";
import { getMyCampaignById, getCampaignRecipients } from "@db/queries/campaigns";
import type { CampaignRecipientStatus } from "@/lib/types";
import { formatPrice } from "@/lib/format";
import {
  PageHeader,
  Card,
  StatCard,
  StatusPill,
  TableShell,
  EmptyState,
  type Tone,
} from "@/components/ui";
import SendCampaignButton from "./send-campaign-button";

export const metadata = { title: "Campaign · Dashboard" };

const RECIPIENT_STATUS_TONE: Record<CampaignRecipientStatus, Tone> = {
  pending: "muted",
  sending: "info",
  sent: "ok",
  failed: "danger",
  skipped_opt_out: "warn",
};

export default async function CampaignDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const row = await getMyCampaignById(user.id, id);
  if (!row) notFound();

  const [segment, recipients] = await Promise.all([
    row.segment_id
      ? db.select({ name: customerSegments.name }).from(customerSegments).where(eq(customerSegments.id, row.segment_id)).then((r) => r[0] ?? null)
      : Promise.resolve(null),
    getCampaignRecipients(id),
  ]);

  const isDraft = row.status === "draft";

  return (
    <div className="space-y-8">
      <PageHeader
        icon={Megaphone}
        title={row.name}
        description={`${row.channel.toUpperCase()} · ${segment?.name ?? "All customers"} · Created ${format(
          new Date(row.created_at),
          "PP"
        )}`}
        actions={isDraft ? <SendCampaignButton campaignId={row.id} /> : undefined}
      />

      <section className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <StatCard
          icon={Users}
          label="Recipients"
          value={isDraft ? "—" : row.recipient_count.toString()}
        />
        <StatCard icon={Send} label="Sent" value={row.sent_count.toString()} />
        <StatCard icon={XCircle} label="Failed" value={row.failed_count.toString()} />
        <StatCard icon={MinusCircle} label="Opted out" value={row.skipped_count.toString()} />
      </section>

      <Card className="max-w-sm">
        <div className="flex items-center justify-between gap-2">
          <p className="text-sm font-medium text-be-text">
            {isDraft ? "Estimated cost" : "Actual cost"}
          </p>
          <Coins className="h-4 w-4 text-be-muted" />
        </div>
        <p className="mt-1 text-2xl font-semibold tabular-nums text-be-text">
          {formatPrice(isDraft ? row.estimated_cost_cents : row.actual_cost_cents, row.currency)}
        </p>
      </Card>

      <Card>
        {row.channel === "email" && row.subject && (
          <p className="mb-2 font-medium text-be-text">{row.subject}</p>
        )}
        <p className="whitespace-pre-wrap text-sm text-be-muted">{row.body}</p>
      </Card>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Recipients</h2>
        {recipients.length === 0 ? (
          <EmptyState
            icon={Users}
            title={isDraft ? "Not sent yet" : "No recipients"}
            body={
              isDraft
                ? "Send this campaign to queue its recipients — sending happens in the background."
                : undefined
            }
          />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Destination</th>
                <th>Status</th>
                <th className="text-right">Cost</th>
                <th>Error</th>
              </tr>
            </thead>
            <tbody>
              {recipients.map((r) => (
                <tr key={r.id}>
                  <td className="font-mono text-be-text">{r.destination}</td>
                  <td>
                    <StatusPill tone={RECIPIENT_STATUS_TONE[r.status]}>
                      {r.status.replace("_", " ")}
                    </StatusPill>
                  </td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(r.cost_cents, row.currency)}
                  </td>
                  <td className="text-be-muted">{r.error ?? "—"}</td>
                </tr>
              ))}
            </tbody>
          </TableShell>
        )}
      </section>
    </div>
  );
}
