import { createFileRoute, Link, Outlet, useRouterState } from "@tanstack/react-router";
import { DashboardLayout } from "@/components/dashboard-layout";
import { DashboardHeader } from "@/components/dashboard/widgets";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Megaphone, Plus, FileText, Image as ImageIcon } from "lucide-react";
import { requireRole } from "@/lib/auth/guards";

export const Route = createFileRoute("/campaigns")({
  beforeLoad: ({ context, location }) => requireRole(context, location, "advertiser", "superadmin"),
  head: () => ({
    meta: [
      { title: "Campaigns — VotersAlert" },
      {
        name: "description",
        content: "Plan, launch and optimize multi-channel political campaigns.",
      },
    ],
  }),
  component: CampaignsLayout,
});

const tabs = [
  { to: "/campaigns", label: "All campaigns", icon: Megaphone, exact: true },
  { to: "/campaigns/drafts", label: "Drafts", icon: FileText },
  { to: "/campaigns/media", label: "Media library", icon: ImageIcon },
];

function CampaignsLayout() {
  const pathname = useRouterState({ select: (r) => r.location.pathname });
  const inWizard = pathname.startsWith("/campaigns/new");

  return (
    <DashboardLayout>
      <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-[1600px] mx-auto">
        {!inWizard && (
          <>
            <DashboardHeader
              eyebrow={
                <>
                  <Megaphone className="h-3 w-3" />
                  <span>12 active · 4 drafts · ₦18.4M lifetime spend</span>
                </>
              }
              title="Campaigns"
              subtitle="Build, schedule and ship multi-channel outreach across SMS, WhatsApp, Voice & paid social."
              actions={
                <Button size="sm" className="gap-1.5" asChild>
                  <Link to="/campaigns/new">
                    <Plus className="h-3.5 w-3.5" /> New campaign
                  </Link>
                </Button>
              }
            />
            <div className="flex items-center gap-1 border-b">
              {tabs.map((t) => {
                const active = t.exact ? pathname === t.to : pathname.startsWith(t.to);
                return (
                  <Link
                    key={t.to}
                    to={t.to}
                    className={cn(
                      "flex items-center gap-1.5 px-3 py-2 text-sm border-b-2 -mb-px transition-colors",
                      active
                        ? "border-primary text-foreground font-medium"
                        : "border-transparent text-muted-foreground hover:text-foreground",
                    )}
                  >
                    <t.icon className="h-3.5 w-3.5" /> {t.label}
                  </Link>
                );
              })}
            </div>
          </>
        )}
        <Outlet />
      </div>
    </DashboardLayout>
  );
}
