import { createFileRoute, Link } from "@tanstack/react-router";
import { DashboardLayout } from "@/components/dashboard-layout";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  ActivityFeed,
  ChartWidget,
  DashboardHeader,
  InsightPanel,
  MetricCard,
  QuickActions,
  Timeline,
} from "@/components/dashboard/widgets";
import {
  ChannelMixChart,
  RevenueLineChart,
  StateReachBarChart,
} from "@/components/dashboard/charts";
import {
  activityFeed,
  adminCampaigns,
  auditTimeline,
  channelMix,
  revenueTrend,
  stateReach,
} from "@/lib/mock-data";
import {
  Activity,
  ArrowUpRight,
  Building2,
  CheckCircle2,
  Download,
  Megaphone,
  Plus,
  ShieldAlert,
  Sparkles,
  TrendingUp,
  UserPlus,
  Users,
  Wallet,
  Zap,
} from "lucide-react";

import { requireRole } from "@/lib/auth/guards";

export const Route = createFileRoute("/admin")({
  beforeLoad: ({ context, location }) => requireRole(context, location, "superadmin"),
  head: () => ({
    meta: [
      { title: "Superadmin — VotersAlert" },
      {
        name: "description",
        content: "Platform-wide operations, revenue, compliance and campaigns.",
      },
    ],
  }),
  component: AdminDashboard,
});

const statusVariant: Record<string, string> = {
  Live: "bg-success/10 text-success border-success/30",
  "Under review": "bg-warning/10 text-warning-foreground border-warning/30",
  Scheduled: "bg-primary/10 text-primary border-primary/30",
  Draft: "bg-muted text-muted-foreground border-border",
};

function AdminDashboard() {
  return (
    <DashboardLayout>
      <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-[1600px] mx-auto">
        <DashboardHeader
          eyebrow={
            <>
              <Activity className="h-3 w-3" />
              <span>Platform control · Last sync 30s ago</span>
            </>
          }
          title="Superadmin overview"
          subtitle="Monitor revenue, compliance and operations across all advertisers."
          actions={
            <>
              <Button variant="outline" size="sm" className="gap-1.5">
                <Download className="h-3.5 w-3.5" /> Export
              </Button>
              <Button size="sm" className="gap-1.5">
                <UserPlus className="h-3.5 w-3.5" /> Invite admin
              </Button>
            </>
          }
        />

        {/* KPI strip */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            label="Monthly revenue"
            value="₦62.4M"
            delta="+12.8%"
            icon={Wallet}
            hint="vs last month"
          />
          <MetricCard
            label="Active advertisers"
            value="184"
            delta="+7"
            icon={Building2}
            accent="accent"
            hint="this week"
          />
          <MetricCard
            label="Campaigns live"
            value="312"
            delta="+24"
            icon={Megaphone}
            hint="across 36 states"
          />
          <MetricCard
            label="Compliance queue"
            value="18"
            delta="-4"
            trend="down"
            icon={ShieldAlert}
            accent="warning"
            hint="awaiting review"
          />
        </div>

        {/* Revenue + Quick Actions */}
        <div className="grid lg:grid-cols-3 gap-4">
          <ChartWidget
            className="lg:col-span-2"
            title="Revenue overview"
            description="Gross billings vs partner payouts, last 8 months."
            badge="₦ millions"
            action={
              <Button variant="ghost" size="sm" className="text-xs gap-1">
                View ledger <ArrowUpRight className="h-3 w-3" />
              </Button>
            }
          >
            <RevenueLineChart data={revenueTrend} />
            <div className="mt-3 grid grid-cols-3 gap-3 text-center text-[11px]">
              <div className="rounded-md bg-muted/40 py-2">
                <div className="text-muted-foreground">MRR</div>
                <div className="font-semibold text-sm tabular-nums">₦62.4M</div>
              </div>
              <div className="rounded-md bg-muted/40 py-2">
                <div className="text-muted-foreground">Take rate</div>
                <div className="font-semibold text-sm tabular-nums">22.6%</div>
              </div>
              <div className="rounded-md bg-muted/40 py-2">
                <div className="text-muted-foreground">Refunds</div>
                <div className="font-semibold text-sm tabular-nums">₦480K</div>
              </div>
            </div>
          </ChartWidget>

          <Card>
            <CardHeader className="pb-2">
              <div className="flex items-center gap-2">
                <Zap className="h-4 w-4 text-primary" />
                <CardTitle className="text-sm">Quick actions</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <QuickActions
                actions={[
                  {
                    label: "Approve advertiser",
                    description: "5 verifications pending KYC review.",
                    icon: CheckCircle2,
                  },
                  {
                    label: "Open compliance queue",
                    description: "18 ads flagged by AI moderation.",
                    icon: ShieldAlert,
                  },
                  {
                    label: "Issue credit",
                    description: "Grant promotional credits to a workspace.",
                    icon: Wallet,
                  },
                  {
                    label: "Broadcast notice",
                    description: "System-wide notice to all advertisers.",
                    icon: Megaphone,
                  },
                ]}
              />
            </CardContent>
          </Card>
        </div>

        {/* Campaign overview + channel mix */}
        <div className="grid lg:grid-cols-3 gap-4">
          <Card className="lg:col-span-2">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
              <div>
                <CardTitle className="text-base">Campaign overview</CardTitle>
                <p className="text-xs text-muted-foreground mt-0.5">
                  Top campaigns by spend, all advertisers
                </p>
              </div>
              <Button variant="ghost" size="sm" className="text-xs gap-1">
                All campaigns <ArrowUpRight className="h-3 w-3" />
              </Button>
            </CardHeader>
            <CardContent className="px-0">
              <Table>
                <TableHeader>
                  <TableRow className="hover:bg-transparent">
                    <TableHead className="text-xs">Advertiser</TableHead>
                    <TableHead className="text-xs hidden md:table-cell">Campaign</TableHead>
                    <TableHead className="text-xs">Status</TableHead>
                    <TableHead className="text-xs text-right">Spend</TableHead>
                    <TableHead className="text-xs text-right">Flags</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {adminCampaigns.map((c) => (
                    <TableRow key={c.name} className="hover:bg-muted/40">
                      <TableCell className="py-3">
                        <div className="font-medium text-sm">{c.advertiser}</div>
                        <div className="text-[11px] text-muted-foreground md:hidden">{c.name}</div>
                      </TableCell>
                      <TableCell className="hidden md:table-cell text-xs text-muted-foreground">
                        {c.name}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant="outline"
                          className={`text-[10px] ${statusVariant[c.status]}`}
                        >
                          {c.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right text-sm font-medium tabular-nums">
                        {c.spend}
                      </TableCell>
                      <TableCell className="text-right">
                        {c.flagged > 0 ? (
                          <Badge
                            variant="outline"
                            className="text-[10px] border-destructive/30 text-destructive"
                          >
                            {c.flagged}
                          </Badge>
                        ) : (
                          <span className="text-[11px] text-muted-foreground">—</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          <ChartWidget title="Channel mix" description="Platform-wide message volume share">
            <ChannelMixChart data={channelMix} />
          </ChartWidget>
        </div>

        {/* Reach + Activity + Timeline */}
        <div className="grid lg:grid-cols-3 gap-4">
          <ChartWidget
            className="lg:col-span-2"
            title="Reach by state"
            description="Top 7 states · last 30 days · K supporters"
            badge="Live"
          >
            <StateReachBarChart data={stateReach} />
          </ChartWidget>

          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center gap-2">
                <Users className="h-4 w-4 text-primary" />
                <CardTitle className="text-sm">Activity feed</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <ActivityFeed items={activityFeed} />
              <Button variant="ghost" size="sm" className="w-full mt-2 text-xs gap-1" asChild>
                <Link to="/notifications">
                  Open notifications <ArrowUpRight className="h-3 w-3" />
                </Link>
              </Button>
            </CardContent>
          </Card>
        </div>

        <div className="grid lg:grid-cols-3 gap-4">
          <Card className="lg:col-span-2">
            <CardHeader className="pb-3">
              <div className="flex items-center gap-2">
                <TrendingUp className="h-4 w-4 text-primary" />
                <CardTitle className="text-sm">Audit timeline · today</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <Timeline items={auditTimeline} />
            </CardContent>
          </Card>

          <InsightPanel
            title="AI platform insights"
            description="Cross-workspace recommendations"
            icon={Sparkles}
            items={[
              {
                title: "3 advertisers near credit cap",
                reason:
                  "Hope Coalition PAC, Unity Movement and Renewal Party will exhaust AI credits within 48 hours at current rate.",
                impact: "Upsell ₦2.1M",
                tone: "primary",
              },
              {
                title: "Compliance false-positive rate up 6%",
                reason:
                  "Hausa script keyword model needs retuning — review last 200 flags before tomorrow.",
                impact: "Action needed",
                tone: "warning",
              },
              {
                title: "New partner gateway online",
                reason: "Niger Telecom voice gateway live in 12 states with 14% lower CPC.",
                impact: "+12 states",
                tone: "accent",
              },
            ]}
          />
        </div>

        <div className="flex items-center justify-end gap-2">
          <Button variant="outline" size="sm" className="gap-1.5">
            <Plus className="h-3.5 w-3.5" /> Add gateway
          </Button>
          <Button size="sm" className="gap-1.5">
            <Sparkles className="h-3.5 w-3.5" /> Tune AI moderation
          </Button>
        </div>
      </div>
    </DashboardLayout>
  );
}
