import Link from "next/link";
import {
  ArrowRight,
  CircleCheck,
  Eye,
  FileText,
  Globe,
  ImageIcon,
  IndianRupee,
  Settings,
  ShoppingBag,
  TrendingUp,
  Users,
} from "lucide-react";

import { OrderStatusBadge } from "@/components/orders/order-status-badge";
import { GlassCard } from "@/components/shared/glass-card";
import { ButtonLink } from "@/components/ui/button-link";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { SiteTrafficStats } from "@/lib/analytics/traffic";
import { formatInr } from "@/lib/format/inr";
import { isOrderPaidStatus } from "@/lib/orders/presentation";
import { cn } from "@/lib/utils";
import type { Order } from "@/types";

const quickLinks = [
  {
    href: "/admin/content",
    label: "Site content",
    description: "Hero copy, banners, and marketing blocks",
    icon: FileText,
  },
  {
    href: "/admin/media",
    label: "Media library",
    description: "Upload and manage site images",
    icon: ImageIcon,
  },
  {
    href: "/admin/settings",
    label: "Settings & SEO",
    description: "Site name, banners, social links, and metadata",
    icon: Settings,
  },
  {
    href: "/admin/orders",
    label: "Orders",
    description: "Payments and checkout history",
    icon: ShoppingBag,
  },
  {
    href: "/admin/users",
    label: "Users",
    description: "Member accounts and roles",
    icon: Users,
  },
] as const;

type StatCardProps = {
  label: string;
  value: string;
  hint?: string;
  icon: typeof IndianRupee;
  accent?: "primary" | "emerald" | "blue" | "muted";
};

const accentStyles = {
  primary: "bg-primary/15 text-primary ring-primary/25",
  emerald: "bg-emerald-500/15 text-emerald-400 ring-emerald-500/25",
  blue: "bg-sky-500/15 text-sky-400 ring-sky-500/25",
  muted: "bg-muted/80 text-muted-foreground ring-border/60",
};

function StatCard({ label, value, hint, icon: Icon, accent = "muted" }: StatCardProps) {
  return (
    <GlassCard className="relative overflow-hidden p-5 sm:p-6">
      <div className="flex items-start justify-between gap-4">
        <div className="min-w-0">
          <p className="text-muted-foreground text-xs font-medium tracking-wider uppercase">
            {label}
          </p>
          <p className="font-display mt-2 truncate text-2xl font-semibold tracking-tight tabular-nums sm:text-3xl">
            {value}
          </p>
          {hint ? (
            <p className="text-muted-foreground mt-1.5 text-xs leading-relaxed">{hint}</p>
          ) : null}
        </div>
        <div
          className={cn(
            "flex size-11 shrink-0 items-center justify-center rounded-xl ring-1 ring-inset",
            accentStyles[accent],
          )}
        >
          <Icon className="size-5" aria-hidden />
        </div>
      </div>
    </GlassCard>
  );
}

function formatOrderWhen(iso: string) {
  return new Intl.DateTimeFormat("en-IN", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(new Date(iso));
}

function formatCount(n: number) {
  return new Intl.NumberFormat("en-IN").format(n);
}

type AdminOverviewProps = {
  orders: Order[];
  userCount: number;
  traffic: SiteTrafficStats;
};

export function AdminOverview({ orders, userCount, traffic }: AdminOverviewProps) {
  const paidOrders = orders.filter((o) => isOrderPaidStatus(o.status));
  const revenue = paidOrders.reduce((sum, o) => sum + o.totalInr, 0);
  const avgPaid =
    paidOrders.length > 0 ? Math.round(revenue / paidOrders.length) : 0;
  const recent = orders.slice(0, 6);

  return (
    <div className="relative space-y-8 sm:space-y-10">
      <div
        className="pointer-events-none absolute inset-x-0 -top-24 h-56 bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-primary/15 via-transparent to-transparent"
        aria-hidden
      />

      <header className="relative flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p className="text-primary text-xs font-semibold tracking-widest uppercase">
            Admin
          </p>
          <h1 className="font-display mt-2 text-3xl font-semibold tracking-tight text-white sm:text-4xl">
            Overview
          </h1>
          <p className="text-muted-foreground mt-2 max-w-xl text-sm leading-relaxed">
            Revenue, site traffic, and members at a glance. Public pages are counted
            automatically — admin and dashboard visits are excluded.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <ButtonLink href="/admin/orders" size="sm" className="rounded-lg">
            All transactions
            <ArrowRight className="size-4" aria-hidden />
          </ButtonLink>
          <ButtonLink href="/" variant="outline" size="sm" className="rounded-lg">
            View site
          </ButtonLink>
        </div>
      </header>

      <section className="relative grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard
          label="Paid revenue"
          value={formatInr(revenue)}
          hint={
            paidOrders.length > 0
              ? `Avg ${formatInr(avgPaid)} per paid order`
              : "No paid orders yet"
          }
          icon={IndianRupee}
          accent="primary"
        />
        <StatCard
          label="Paid orders"
          value={String(paidOrders.length)}
          hint={`${orders.length} total in database`}
          icon={CircleCheck}
          accent="emerald"
        />
        <StatCard
          label="Transactions"
          value={String(orders.length)}
          hint="All checkout attempts"
          icon={ShoppingBag}
          accent="blue"
        />
        <StatCard
          label="Users"
          value={String(userCount)}
          hint="Registered accounts"
          icon={Users}
          accent="muted"
        />
      </section>

      <section className="relative">
        <div className="mb-4">
          <h2 className="font-display text-lg font-semibold tracking-tight text-white sm:text-xl">
            Site traffic
          </h2>
          <p className="text-muted-foreground mt-1 text-sm">
            Page views and unique visitors (last 7 days in parentheses where shown)
          </p>
        </div>
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          <StatCard
            label="Views today"
            value={formatCount(traffic.pageViewsToday)}
            hint={`${formatCount(traffic.uniqueVisitorsToday)} unique visitors`}
            icon={Eye}
            accent="blue"
          />
          <StatCard
            label="Views (7 days)"
            value={formatCount(traffic.pageViews7d)}
            hint={`${formatCount(traffic.uniqueVisitors7d)} unique visitors`}
            icon={TrendingUp}
            accent="primary"
          />
          <StatCard
            label="Views (30 days)"
            value={formatCount(traffic.pageViews30d)}
            hint="Rolling month of public pages"
            icon={Globe}
            accent="emerald"
          />
          <StatCard
            label="Top page (7d)"
            value={
              traffic.topPages[0]
                ? traffic.topPages[0].path
                : "—"
            }
            hint={
              traffic.topPages[0]
                ? `${formatCount(traffic.topPages[0].views)} views`
                : "Browse the site to collect data"
            }
            icon={Globe}
            accent="muted"
          />
        </div>

        {traffic.topPages.length > 0 ? (
          <GlassCard className="mt-4 overflow-hidden p-0">
            <Table>
              <TableHeader>
                <TableRow className="hover:bg-transparent">
                  <TableHead className="pl-6">Page</TableHead>
                  <TableHead className="pr-6 text-right">Views (7d)</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {traffic.topPages.map((row) => (
                  <TableRow key={row.path}>
                    <TableCell className="pl-6 font-mono text-xs">{row.path}</TableCell>
                    <TableCell className="pr-6 text-right tabular-nums">
                      {formatCount(row.views)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </GlassCard>
        ) : null}
      </section>

      <section className="relative">
        <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
          <div>
            <h2 className="font-display text-lg font-semibold tracking-tight text-white sm:text-xl">
              Quick links
            </h2>
            <p className="text-muted-foreground mt-1 text-sm">
              Jump to the tools you use most
            </p>
          </div>
        </div>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {quickLinks.map((item) => {
            const Icon = item.icon;
            return (
              <Link key={item.href} href={item.href} className="group block h-full">
                <GlassCard className="flex h-full flex-col p-5 transition-premium group-hover:border-primary/30">
                  <Icon className="text-primary size-5" aria-hidden />
                  <p className="mt-3 font-medium text-foreground">{item.label}</p>
                  <p className="text-muted-foreground mt-1 flex-1 text-xs leading-relaxed">
                    {item.description}
                  </p>
                  <span className="text-primary mt-4 inline-flex items-center gap-1 text-xs font-medium">
                    Open
                    <ArrowRight
                      className="size-3.5 transition-transform group-hover:translate-x-0.5"
                      aria-hidden
                    />
                  </span>
                </GlassCard>
              </Link>
            );
          })}
        </div>
      </section>

      <section className="relative">
        <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
          <div>
            <h2 className="font-display text-lg font-semibold tracking-tight text-white sm:text-xl">
              Recent transactions
            </h2>
            <p className="text-muted-foreground mt-1 text-sm">
              Latest checkouts — newest first
            </p>
          </div>
          {orders.length > 0 ? (
            <ButtonLink
              href="/admin/orders"
              variant="outline"
              size="sm"
              className="rounded-lg"
            >
              View all
            </ButtonLink>
          ) : null}
        </div>

        <GlassCard className="overflow-hidden p-0">
          {recent.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow className="hover:bg-transparent">
                  <TableHead className="pl-6">Order</TableHead>
                  <TableHead>Customer</TableHead>
                  <TableHead className="text-right">Total</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="pr-6 text-right">Date</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {recent.map((o) => (
                  <TableRow key={o.id} className="group">
                    <TableCell className="pl-6 font-mono text-xs">
                      <span className="text-foreground">{o.id.slice(0, 8)}</span>
                      <span className="text-muted-foreground">…</span>
                    </TableCell>
                    <TableCell className="max-w-[200px] truncate">{o.userEmail}</TableCell>
                    <TableCell className="text-right font-medium tabular-nums">
                      {formatInr(o.totalInr)}
                    </TableCell>
                    <TableCell>
                      <OrderStatusBadge status={o.status} />
                    </TableCell>
                    <TableCell className="text-muted-foreground pr-6 text-right text-xs whitespace-nowrap">
                      {formatOrderWhen(o.createdAt)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <div className="flex flex-col items-center px-6 py-16 text-center">
              <div className="bg-muted/50 flex size-14 items-center justify-center rounded-2xl">
                <ShoppingBag className="text-muted-foreground size-7" aria-hidden />
              </div>
              <p className="mt-4 font-medium text-foreground">No transactions yet</p>
              <p className="text-muted-foreground mt-2 max-w-sm text-sm leading-relaxed">
                Complete a demo checkout on the site to see orders appear here.
              </p>
              <ButtonLink href="/checkout" className="mt-6 rounded-lg" size="sm">
                Go to checkout
              </ButtonLink>
            </div>
          )}
        </GlassCard>
      </section>
    </div>
  );
}
