import Link from "next/link";
import { redirect } from "next/navigation";
import { format } from "date-fns";
import { Megaphone, Plus, ChevronRight } from "lucide-react";
import { getDashboardUser } from "@/lib/view-as";
import { getMyCampaigns } from "@db/queries/campaigns";
import type { CampaignStatus } from "@/lib/types";
import { formatPrice } from "@/lib/format";
import { PageHeader, LinkButton, EmptyState, StatusPill, TableShell, type Tone } from "@/components/ui";

export const metadata = { title: "Campaigns · Dashboard" };

const STATUS_TONE: Record<CampaignStatus, Tone> = {
  draft: "muted",
  queued: "info",
  sending: "info",
  sent: "ok",
  failed: "danger",
};

export default async function CampaignsPage() {
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const campaigns = await getMyCampaigns(user.id);

  return (
    <div className="space-y-6">
      <PageHeader
        icon={Megaphone}
        title="Campaigns"
        description="Reach fans who said yes. SMS and email campaigns go to opted-in contacts only."
        actions={
          <LinkButton href="/dashboard/campaigns/new" icon={Plus}>
            New campaign
          </LinkButton>
        }
      />

      {campaigns.length === 0 ? (
        <EmptyState
          icon={Megaphone}
          title="No campaigns yet"
          body="Compose an SMS or email blast and send it to a segment, or every customer you have."
          action={
            <LinkButton href="/dashboard/campaigns/new" icon={Plus}>
              New campaign
            </LinkButton>
          }
        />
      ) : (
        <TableShell>
          <thead>
            <tr>
              <th>Name</th>
              <th>Channel</th>
              <th>Status</th>
              <th className="text-right">Sent / recipients</th>
              <th className="text-right">Cost</th>
              <th>Created</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {campaigns.map((c) => (
              <tr key={c.id}>
                <td className="font-medium text-be-text">{c.name}</td>
                <td className="text-be-muted uppercase">{c.channel}</td>
                <td>
                  <StatusPill tone={STATUS_TONE[c.status]}>{c.status}</StatusPill>
                </td>
                <td className="text-right tabular-nums text-be-text">
                  {c.status === "draft" ? "—" : `${c.sent_count} / ${c.recipient_count}`}
                </td>
                <td className="text-right tabular-nums text-be-text">
                  {formatPrice(c.status === "draft" ? c.estimated_cost_cents : c.actual_cost_cents, c.currency)}
                </td>
                <td className="whitespace-nowrap text-be-muted">
                  {format(new Date(c.created_at), "PP")}
                </td>
                <td className="text-right">
                  <Link
                    href={`/dashboard/campaigns/${c.id}`}
                    className="inline-flex items-center gap-1 text-sm font-medium text-brand-green-h hover:underline"
                  >
                    View <ChevronRight className="h-3.5 w-3.5" />
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </TableShell>
      )}
    </div>
  );
}
