import { createFileRoute } from "@tanstack/react-router";
import { DashboardLayout } from "@/components/dashboard-layout";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { DashboardHeader, MetricCard } from "@/components/dashboard/widgets";
import {
  ArrowDownToLine,
  CreditCard,
  Download,
  Plus,
  Receipt,
  Wallet,
  Banknote,
  Sparkles,
} from "lucide-react";
import { walletBalance, fundingMethods, transactions, invoices, fmtNGN } from "@/lib/billing-data";
import { requireRole } from "@/lib/auth/guards";

export const Route = createFileRoute("/wallet")({
  beforeLoad: ({ context, location }) => requireRole(context, location, "advertiser", "superadmin"),
  head: () => ({ meta: [{ title: "Wallet & Billing — VotersAlert" }] }),
  component: WalletPage,
});

function WalletPage() {
  const usagePct = Math.round((walletBalance.monthlySpend / walletBalance.monthlyBudget) * 100);
  return (
    <DashboardLayout>
      <div className="p-4 md:p-6 space-y-6 animate-fade-in">
        <DashboardHeader
          eyebrow={
            <>
              <Wallet className="h-3 w-3" /> Billing
            </>
          }
          title="Wallet & Billing"
          subtitle="Top up your balance, monitor spend, and download invoices."
          actions={
            <>
              <Button variant="outline">
                <Download className="h-4 w-4" /> Statement
              </Button>
              <Button>
                <Plus className="h-4 w-4" /> Add funds
              </Button>
            </>
          }
        />

        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          <Card className="lg:col-span-2 overflow-hidden relative">
            <div className="absolute inset-0 bg-gradient-to-br from-primary/10 via-accent/5 to-transparent pointer-events-none" />
            <CardContent className="pt-6 relative">
              <div className="text-xs text-muted-foreground">Available balance</div>
              <div className="mt-1 text-4xl font-semibold tracking-tight tabular-nums">
                {fmtNGN(walletBalance.available)}
              </div>
              <div className="mt-1 text-xs text-muted-foreground">
                + {fmtNGN(walletBalance.reserved)} reserved for live campaigns
              </div>
              <div className="mt-5 space-y-1.5">
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">Monthly spend</span>
                  <span className="font-medium tabular-nums">
                    {fmtNGN(walletBalance.monthlySpend)} / {fmtNGN(walletBalance.monthlyBudget)}
                  </span>
                </div>
                <Progress value={usagePct} className="h-1.5" />
              </div>
              <div className="mt-5 flex gap-2 flex-wrap">
                <Button size="sm">
                  <Plus className="h-3.5 w-3.5" /> Add funds
                </Button>
                <Button size="sm" variant="outline">
                  <ArrowDownToLine className="h-3.5 w-3.5" /> Withdraw
                </Button>
                <Button size="sm" variant="ghost">
                  <Sparkles className="h-3.5 w-3.5" /> Auto top-up
                </Button>
              </div>
            </CardContent>
          </Card>
          <MetricCard
            label="This month"
            value={fmtNGN(walletBalance.monthlySpend)}
            delta="+12.4%"
            trend="up"
            icon={Banknote}
            accent="accent"
          />
          <MetricCard
            label="Pending invoices"
            value="0"
            hint="All paid"
            icon={Receipt}
            accent="primary"
          />
        </div>

        <Tabs defaultValue="transactions" className="space-y-4">
          <TabsList>
            <TabsTrigger value="transactions">Transactions</TabsTrigger>
            <TabsTrigger value="invoices">Invoices</TabsTrigger>
            <TabsTrigger value="funding">Funding methods</TabsTrigger>
            <TabsTrigger value="topup">Top up</TabsTrigger>
          </TabsList>

          <TabsContent value="transactions">
            <Card>
              <CardHeader className="flex-row items-center justify-between space-y-0">
                <div>
                  <CardTitle>Recent transactions</CardTitle>
                  <CardDescription>Last 30 days of wallet activity.</CardDescription>
                </div>
                <Button variant="outline" size="sm">
                  <Download className="h-3.5 w-3.5" /> Export CSV
                </Button>
              </CardHeader>
              <CardContent className="p-0 overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Reference</TableHead>
                      <TableHead>Date</TableHead>
                      <TableHead>Description</TableHead>
                      <TableHead>Channel</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                      <TableHead>Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {transactions.map((t) => (
                      <TableRow key={t.id}>
                        <TableCell className="font-mono text-xs">{t.id}</TableCell>
                        <TableCell className="text-xs whitespace-nowrap">{t.date}</TableCell>
                        <TableCell className="max-w-[280px] truncate">{t.desc}</TableCell>
                        <TableCell>
                          <Badge variant="secondary" className="text-[10px]">
                            {t.channel}
                          </Badge>
                        </TableCell>
                        <TableCell
                          className={`text-right tabular-nums font-medium ${t.amount > 0 ? "text-success" : ""}`}
                        >
                          {t.amount > 0 ? "+" : ""}
                          {fmtNGN(t.amount)}
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant={
                              t.status === "Completed"
                                ? "default"
                                : t.status === "Pending"
                                  ? "secondary"
                                  : "outline"
                            }
                            className="text-[10px]"
                          >
                            {t.status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="invoices">
            <Card>
              <CardHeader>
                <CardTitle>Invoices & receipts</CardTitle>
                <CardDescription>
                  Download tax-ready invoices for every billing period.
                </CardDescription>
              </CardHeader>
              <CardContent className="p-0 overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Invoice</TableHead>
                      <TableHead>Period</TableHead>
                      <TableHead>Due</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="text-right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {invoices.map((i) => (
                      <TableRow key={i.id}>
                        <TableCell className="font-mono text-xs">{i.id}</TableCell>
                        <TableCell>{i.period}</TableCell>
                        <TableCell className="text-xs">{i.due}</TableCell>
                        <TableCell className="text-right tabular-nums font-medium">
                          {fmtNGN(i.amount)}
                        </TableCell>
                        <TableCell>
                          <Badge className="text-[10px]" variant="secondary">
                            {i.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">
                          <Button variant="ghost" size="sm">
                            <Download className="h-3.5 w-3.5" /> PDF
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="funding">
            <div className="grid gap-4 md:grid-cols-3">
              {fundingMethods.map((m) => (
                <Card key={m.id} className="relative">
                  <CardContent className="pt-5">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="h-9 w-9 rounded-md bg-primary/10 flex items-center justify-center">
                          <CreditCard className="h-4 w-4 text-primary" />
                        </div>
                        <div>
                          <div className="text-sm font-medium">{m.brand}</div>
                          <div className="text-xs text-muted-foreground">
                            •••• {m.last4} · exp {m.exp}
                          </div>
                        </div>
                      </div>
                      {m.primary && <Badge className="text-[10px]">Primary</Badge>}
                    </div>
                    <div className="mt-4 flex gap-2">
                      <Button size="sm" variant="outline">
                        Manage
                      </Button>
                      {!m.primary && (
                        <Button size="sm" variant="ghost">
                          Make primary
                        </Button>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
              <Card className="border-dashed flex items-center justify-center min-h-[140px]">
                <Button variant="ghost">
                  <Plus className="h-4 w-4" /> Add payment method
                </Button>
              </Card>
            </div>
          </TabsContent>

          <TabsContent value="topup">
            <Card className="max-w-xl">
              <CardHeader>
                <CardTitle>Top up wallet</CardTitle>
                <CardDescription>
                  Funds reflect within 60 seconds for cards and 5 minutes for bank transfers.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-4 gap-2">
                  {[500_000, 1_000_000, 2_500_000, 5_000_000].map((a) => (
                    <Button key={a} variant="outline" size="sm" className="tabular-nums">
                      {fmtNGN(a)}
                    </Button>
                  ))}
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-medium">Custom amount (NGN)</label>
                  <Input type="number" placeholder="0" />
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-medium">Payment method</label>
                  <div className="rounded-md border p-3 text-sm flex items-center justify-between">
                    <span className="flex items-center gap-2">
                      <CreditCard className="h-4 w-4" /> Visa •••• 4242
                    </span>
                    <Button variant="ghost" size="sm">
                      Change
                    </Button>
                  </div>
                </div>
                <Button className="w-full">Confirm top-up</Button>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </DashboardLayout>
  );
}
