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 { Progress } from "@/components/ui/progress";
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, ReachAreaChart } from "@/components/dashboard/charts";
import {
  activityFeed,
  advertiserCampaigns,
  aiSuggestions,
  auditTimeline,
  channelMix,
  reachTrend,
} from "@/lib/mock-data";
import {
  Activity,
  ArrowUpRight,
  CreditCard,
  Download,
  Megaphone,
  MousePointerClick,
  Plus,
  Send,
  ShieldCheck,
  Sparkles,
  Users,
  Wallet,
  Zap,
} from "lucide-react";

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

export const Route = createFileRoute("/")({
  beforeLoad: ({ context, location }) => requireAuth(context, location),
  head: () => ({
    meta: [
      { title: "Dashboard — VotersAlert" },
      {
        name: "description",
        content: "Overview of your political campaigns, reach, and compliance.",
      },
    ],
  }),
  component: AdvertiserDashboard,
});

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 AdvertiserDashboard() {
  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>Real-time overview · Hope Coalition PAC</span>
            </>
          }
          title="Welcome back, Adaeze"
          subtitle="Here's what's happening across your campaigns today."
          actions={
            <>
              <Button variant="outline" size="sm" className="gap-1.5">
                <Download className="h-3.5 w-3.5" /> Export report
              </Button>
              <Button size="sm" className="gap-1.5">
                <Plus className="h-3.5 w-3.5" /> New campaign
              </Button>
            </>
          }
        />

        {/* KPIs */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            label="Active campaigns"
            value="12"
            delta="+3"
            icon={Megaphone}
            hint="this week"
          />
          <MetricCard
            label="Reach (30d)"
            value="4.82M"
            delta="+18.4%"
            icon={Users}
            accent="accent"
            hint="supporters"
          />
          <MetricCard
            label="Messages sent"
            value="1.24M"
            delta="+9.1%"
            icon={Send}
            hint="across 4 channels"
          />
          <MetricCard
            label="Engagement rate"
            value="6.1%"
            delta="+0.8pp"
            icon={MousePointerClick}
            accent="accent"
            hint="CTR + replies"
          />
        </div>

        {/* Reach trend + wallet */}
        <div className="grid lg:grid-cols-3 gap-4">
          <ChartWidget
            className="lg:col-span-2"
            title="Reach & engagement"
            description="Last 7 days · all live campaigns"
            badge="Live"
            action={
              <Button variant="ghost" size="sm" className="text-xs gap-1">
                Analytics <ArrowUpRight className="h-3 w-3" />
              </Button>
            }
          >
            <ReachAreaChart data={reachTrend} />
            <div className="mt-3 flex items-center gap-4 text-[11px] text-muted-foreground">
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-sm bg-chart-1" /> Reach
              </span>
              <span className="flex items-center gap-1.5">
                <span className="h-2 w-2 rounded-sm bg-chart-2" /> Engaged
              </span>
            </div>
          </ChartWidget>

          <Card className="bg-gradient-to-br from-primary/5 via-accent/5 to-transparent border-primary/20">
            <CardHeader className="pb-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Wallet className="h-4 w-4 text-primary" />
                  <CardTitle className="text-sm">Wallet</CardTitle>
                </div>
                <Badge variant="secondary" className="text-[10px] h-4">
                  NGN
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <div className="text-[11px] text-muted-foreground">Available balance</div>
                <div className="mt-0.5 text-3xl font-semibold tracking-tight tabular-nums">
                  ₦8,420,500
                </div>
                <div className="mt-1 text-[11px] text-success flex items-center gap-1">
                  <ArrowUpRight className="h-3 w-3" /> +₦1.2M this week
                </div>
              </div>

              <div className="space-y-1.5">
                <div className="flex justify-between text-[11px]">
                  <span className="text-muted-foreground">Monthly burn</span>
                  <span className="font-medium">₦6.4M / ₦10M cap</span>
                </div>
                <Progress value={64} className="h-1.5" />
              </div>

              <div className="grid grid-cols-2 gap-2">
                <Button size="sm" className="gap-1.5">
                  <Plus className="h-3.5 w-3.5" /> Top up
                </Button>
                <Button size="sm" variant="outline" className="gap-1.5">
                  <CreditCard className="h-3.5 w-3.5" /> Invoices
                </Button>
              </div>

              <div className="rounded-md border border-border/60 bg-background/60 p-2.5 text-[11px]">
                <div className="font-medium">Next auto-debit</div>
                <div className="text-muted-foreground mt-0.5">
                  ₦420,000 · Lagos Youth Mobilization · Tomorrow 09:00
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Campaigns + AI Suggestions */}
        <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">Recent campaigns</CardTitle>
                <p className="text-xs text-muted-foreground mt-0.5">Updated 2 minutes ago</p>
              </div>
              <Button variant="ghost" size="sm" className="text-xs gap-1">
                View all <ArrowUpRight className="h-3 w-3" />
              </Button>
            </CardHeader>
            <CardContent className="px-0">
              <Table>
                <TableHeader>
                  <TableRow className="hover:bg-transparent">
                    <TableHead className="text-xs">Campaign</TableHead>
                    <TableHead className="text-xs hidden md:table-cell">Region</TableHead>
                    <TableHead className="text-xs">Status</TableHead>
                    <TableHead className="text-xs text-right">Reach</TableHead>
                    <TableHead className="text-xs text-right hidden sm:table-cell">CTR</TableHead>
                    <TableHead className="text-xs text-right">Spend</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {advertiserCampaigns.map((c) => (
                    <TableRow key={c.name} className="hover:bg-muted/40">
                      <TableCell className="py-3">
                        <div className="font-medium text-sm">{c.name}</div>
                        <div className="text-[11px] text-muted-foreground">{c.channel}</div>
                      </TableCell>
                      <TableCell className="hidden md:table-cell text-xs text-muted-foreground">
                        {c.region}
                      </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.reach}
                      </TableCell>
                      <TableCell className="text-right text-sm tabular-nums hidden sm:table-cell">
                        {c.ctr}
                      </TableCell>
                      <TableCell className="text-right text-sm tabular-nums">{c.spend}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          <InsightPanel
            title="AI suggestions"
            description="Personalized for your campaigns"
            icon={Sparkles}
            items={aiSuggestions}
          />
        </div>

        {/* Channel mix + engagement + activity */}
        <div className="grid lg:grid-cols-3 gap-4">
          <ChartWidget title="Channel mix" description="Message share across your live campaigns">
            <ChannelMixChart data={channelMix} />
          </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: "Launch campaign",
                    description: "Spin up a new outreach in 4 steps.",
                    icon: Megaphone,
                  },
                  {
                    label: "Generate ad copy",
                    description: "AI Studio drafts compliant variants.",
                    icon: Sparkles,
                  },
                  {
                    label: "Top up wallet",
                    description: "Add credit via card or bank transfer.",
                    icon: Wallet,
                  },
                  {
                    label: "Compliance check",
                    description: "Pre-screen creative before launch.",
                    icon: ShieldCheck,
                  },
                ]}
              />
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center gap-2">
                <Users className="h-4 w-4 text-primary" />
                <CardTitle className="text-sm">Workspace activity</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <ActivityFeed items={activityFeed.slice(0, 5)} />
            </CardContent>
          </Card>
        </div>

        {/* Timeline */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Activity className="h-4 w-4 text-primary" />
                <CardTitle className="text-sm">Today's timeline</CardTitle>
              </div>
              <Button variant="ghost" size="sm" className="text-xs gap-1" asChild>
                <Link to="/notifications">
                  All notifications <ArrowUpRight className="h-3 w-3" />
                </Link>
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <Timeline items={auditTimeline} />
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
