'use client';

import { useState } from 'react';
import { motion, AnimatePresence, Variants } from 'framer-motion';
import { useRouter } from 'next/navigation';
import {
  Users,
  ShoppingCart,
  Package,
  TrendingUp,
  Clock,
  CheckCircle2,
  Truck,
  XCircle,
  ArrowRight,
  Loader2,
  RefreshCw,
  BarChart2,
  AlertCircle,
  Calendar,
} from 'lucide-react';
import { useUser } from '@/store/auth.store';
import { useAdminStats, StatPeriod } from '@/hooks/useAdmin';
import { formatIDR, formatDate } from '@/lib/utils';
import type { Order, RevenueChartItem } from '@/types';

import Image from 'next/image';
// ── Period Config ───────────────────────────────────────────────────────
const PERIODS: {
  key: StatPeriod;
  label: string;
  shortLabel: string;
  desc: string;
}[] = [
  {
    key: 'today',
    label: 'Hari Ini',
    shortLabel: 'Hari Ini',
    desc: 'Data hari ini saja',
  },
  {
    key: 'week',
    label: 'Minggu Ini',
    shortLabel: 'Minggu Ini',
    desc: 'Data 7 hari terakhir',
  },
  {
    key: 'month',
    label: 'Bulan Ini',
    shortLabel: 'Bulan Ini',
    desc: 'Data bulan berjalan',
  },
  {
    key: 'year',
    label: 'Tahun Ini',
    shortLabel: 'Tahun Ini',
    desc: 'Data tahun berjalan',
  },
];

// ── Animations ─────────────────────────────────────────────────────────
const fadeUp: Variants = {
  hidden: { opacity: 0, y: 16 },
  visible: (i = 0) => ({
    opacity: 1,
    y: 0,
    transition: { delay: i * 0.07, duration: 0.4, ease: 'easeOut' },
  }),
};

// ── Status Config ───────────────────────────────────────────────────────
const statusConfig: Record<
  string,
  { label: string; icon: React.ReactNode; className: string }
> = {
  pending: {
    label: 'Menunggu',
    icon: <Clock className="w-3 h-3" />,
    className: 'text-amber-700 bg-amber-50 border-amber-200',
  },
  confirmed: {
    label: 'Dikonfirmasi',
    icon: <CheckCircle2 className="w-3 h-3" />,
    className: 'text-blue-700 bg-blue-50 border-blue-200',
  },
  processing: {
    label: 'Diproses',
    icon: <Package className="w-3 h-3" />,
    className: 'text-indigo-700 bg-indigo-50 border-indigo-200',
  },
  shipped: {
    label: 'Dikirim',
    icon: <Truck className="w-3 h-3" />,
    className: 'text-purple-700 bg-purple-50 border-purple-200',
  },
  delivered: {
    label: 'Terkirim',
    icon: <CheckCircle2 className="w-3 h-3" />,
    className: 'text-green-700 bg-green-50 border-green-200',
  },
  completed: {
    label: 'Selesai',
    icon: <CheckCircle2 className="w-3 h-3" />,
    className: 'text-emerald-700 bg-emerald-50 border-emerald-200',
  },
  refunded: {
    label: 'Direfund',
    icon: <XCircle className="w-3 h-3" />,
    className: 'text-gray-700 bg-gray-50 border-gray-200',
  },
  cancelled: {
    label: 'Dibatalkan',
    icon: <XCircle className="w-3 h-3" />,
    className: 'text-red-700 bg-red-50 border-red-200',
  },
};

// ── Status Badge ────────────────────────────────────────────────────────
function StatusBadge({ status }: { status: string }) {
  const config = statusConfig[status] ?? {
    label: status,
    icon: null,
    className: 'text-gray-700 bg-gray-50 border-gray-200',
  };
  return (
    <span
      className={`inline-flex items-center gap-1.5 text-xs font-bold px-2.5 py-1 rounded-full border ${config.className}`}
    >
      {config.icon}
      {config.label}
    </span>
  );
}

// ── Skeleton Components ─────────────────────────────────────────────────
function StatCardSkeleton() {
  return (
    <div className="bg-white/60 backdrop-blur-sm rounded-2xl p-5 border border-gray-200 animate-pulse">
      <div className="flex items-center justify-between mb-4">
        <div className="w-10 h-10 rounded-xl bg-gray-200" />
        <div className="w-16 h-6 rounded-full bg-gray-200" />
      </div>
      <div className="h-8 w-24 bg-gray-200 rounded mb-2" />
      <div className="h-4 w-32 bg-gray-200 rounded" />
    </div>
  );
}

function ChartSkeleton() {
  return (
    <div className="bg-white/60 backdrop-blur-sm rounded-2xl border border-gray-200 p-6 animate-pulse">
      <div className="h-4 w-32 bg-gray-200 rounded mb-1" />
      <div className="h-3 w-24 bg-gray-200 rounded mb-6" />
      <div className="h-40 bg-gray-100 rounded-xl" />
    </div>
  );
}

// ── Bar Chart (SVG pure) ────────────────────────────────────────────────
// Formats ISO period string (e.g. '2026-05-01T00:00:00Z') → 'Mei'
function fmtPeriod(period: string): string {
  try {
    return new Date(period).toLocaleDateString('id-ID', { month: 'short' });
  } catch {
    return period;
  }
}

function MonthlyBarChart({ data }: { data: RevenueChartItem[] }) {
  if (!data.length) {
    return (
      <div className="h-40 flex flex-col items-center justify-center gap-2 text-gray-300">
        <BarChart2 className="w-8 h-8" />
        <p className="text-xs font-medium">Belum ada data bulanan</p>
      </div>
    );
  }
  const maxOrders = Math.max(...data.map((m) => m.orders));
  return (
    <div className="relative h-44">
      {/* Y-axis */}
      <div className="absolute left-0 top-0 bottom-6 flex flex-col justify-between pr-2">
        {[maxOrders, Math.round(maxOrders / 2), 0].map((v, i) => (
          <span
            key={i}
            className="text-[10px] text-gray-400 w-8 text-right leading-none"
          >
            {v}
          </span>
        ))}
      </div>
      {/* Bars */}
      <div className="ml-10 h-full flex items-end gap-1.5 pb-6">
        {data.map((m, i) => (
          <div
            key={m.period}
            className="flex-1 flex flex-col items-center gap-1 group"
          >
            <div className="relative w-full">
              <motion.div
                initial={{ scaleY: 0, originY: 1 }}
                animate={{ scaleY: 1, originY: 1 }}
                transition={{ duration: 0.5, delay: i * 0.06 }}
                style={{
                  height: `${maxOrders > 0 ? (m.orders / maxOrders) * 120 : 4}px`,
                }}
                className="w-full bg-linear-to-t from-yellow-500 to-yellow-300 rounded-t-md min-h-1 relative cursor-default"
              >
                <div className="absolute -top-7 left-1/2 -translate-x-1/2 bg-gray-900 text-white text-[10px] px-2 py-0.5 rounded-md whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10">
                  {m.orders} pesanan
                </div>
              </motion.div>
            </div>
            <span className="text-[10px] text-gray-400 leading-none">
              {fmtPeriod(m.period)}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Revenue Sparkline (SVG pure) ────────────────────────────────────────
function RevenueSparkline({ data }: { data: RevenueChartItem[] }) {
  if (!data.length) {
    return (
      <div className="h-20 flex items-center justify-center text-gray-300 text-xs font-medium">
        Belum ada data
      </div>
    );
  }
  const W = 280,
    H = 80,
    pad = 6;
  const max = Math.max(...data.map((m) => m.revenue));
  const safeMax = max === 0 ? 1 : max;
  const points = data
    .map((m, i) => {
      const x = pad + (i / Math.max(data.length - 1, 1)) * (W - pad * 2);
      const y = H - pad - (m.revenue / safeMax) * (H - pad * 2);
      return `${x},${y}`;
    })
    .join(' ');
  const area = `${pad},${H - pad} ${points} ${W - pad},${H - pad}`;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="w-full overflow-visible">
      <defs>
        <linearGradient id="rev-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#eab308" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#eab308" stopOpacity="0" />
        </linearGradient>
      </defs>
      <polygon points={area} fill="url(#rev-fill)" />
      <polyline
        points={points}
        fill="none"
        stroke="#eab308"
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      {(() => {
        const last = data[data.length - 1];
        const i = data.length - 1;
        const x = pad + (i / Math.max(data.length - 1, 1)) * (W - pad * 2);
        const y = H - pad - (last.revenue / safeMax) * (H - pad * 2);
        return (
          <>
            <circle
              cx={x}
              cy={y}
              r="5"
              fill="white"
              stroke="#eab308"
              strokeWidth="2.5"
            />
            <circle cx={x} cy={y} r="2.5" fill="#eab308" />
          </>
        );
      })()}
    </svg>
  );
}

// ── Order Status Overview ───────────────────────────────────────────────
const STATUS_OVERVIEW = [
  {
    key: 'pending' as const,
    label: 'Menunggu',
    icon: <Clock className="w-4 h-4" />,
    color: 'text-amber-600 bg-amber-50 border-amber-200',
  },
  {
    key: 'processing' as const,
    label: 'Diproses',
    icon: <Package className="w-4 h-4" />,
    color: 'text-indigo-600 bg-indigo-50 border-indigo-200',
  },
  {
    key: 'shipped' as const,
    label: 'Dikirim',
    icon: <Truck className="w-4 h-4" />,
    color: 'text-purple-600 bg-purple-50 border-purple-200',
  },
  {
    key: 'confirmed' as const,
    label: 'Dikonfirmasi',
    icon: <CheckCircle2 className="w-4 h-4" />,
    color: 'text-blue-600 bg-blue-50 border-blue-200',
  },
  {
    key: 'completed' as const,
    label: 'Selesai',
    icon: <CheckCircle2 className="w-4 h-4" />,
    color: 'text-emerald-600 bg-emerald-50 border-emerald-200',
  },
  {
    key: 'cancelled' as const,
    label: 'Dibatalkan',
    icon: <XCircle className="w-4 h-4" />,
    color: 'text-red-600 bg-red-50 border-red-200',
  },
];

type OrderStatusCounts = {
  pending: number;
  confirmed: number;
  processing: number;
  shipped: number;
  cancelled?: number;
  completed?: number;
};

function OrderStatusOverview({
  counts,
  isLoading,
}: {
  counts: OrderStatusCounts | undefined;
  isLoading: boolean;
}) {
  return (
    <motion.div
      initial="hidden"
      animate="visible"
      variants={fadeUp}
      custom={4.5}
      className="grid grid-cols-3 sm:grid-cols-6 gap-3 mb-6"
    >
      {STATUS_OVERVIEW.map((s, i) =>
        isLoading ? (
          <div
            key={s.key}
            className="bg-white/60 backdrop-blur-sm rounded-xl p-4 border border-gray-200 animate-pulse h-20"
          />
        ) : (
          <motion.div
            key={s.key}
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ delay: 0.4 + i * 0.06 }}
            className="flex items-center gap-3 rounded-xl px-4 py-3.5 border bg-white/60 backdrop-blur-sm hover:shadow-sm transition-all cursor-default"
          >
            <div className={`p-2 rounded-lg border ${s.color}`}>{s.icon}</div>
            <div>
              <p className="text-xl font-black text-gray-900 leading-none">
                {counts?.[s.key] ?? 0}
              </p>
              <p className="text-[11px] font-medium text-gray-500 mt-0.5">
                {s.label}
              </p>
            </div>
          </motion.div>
        )
      )}
    </motion.div>
  );
}

// ── Period Selector ─────────────────────────────────────────────────────
function PeriodSelector({
  value,
  onChange,
}: {
  value: StatPeriod;
  onChange: (p: StatPeriod) => void;
}) {
  return (
    <div className="flex items-center gap-1 bg-gray-100/80 rounded-xl p-1">
      {PERIODS.map((p) => (
        <button
          key={p.key}
          onClick={() => onChange(p.key)}
          className={`relative px-3 py-1.5 rounded-lg text-xs font-bold tracking-wide transition-all ${
            value === p.key
              ? 'bg-white text-gray-900 shadow-sm'
              : 'text-gray-500 hover:text-gray-700'
          }`}
        >
          {value === p.key && (
            <motion.span
              layoutId="period-pill"
              className="absolute inset-0 bg-white rounded-lg shadow-sm"
              transition={{ type: 'spring', bounce: 0.2, duration: 0.3 }}
            />
          )}
          <span className="relative z-10">{p.label}</span>
        </button>
      ))}
    </div>
  );
}

// ── Period Context Badge ─────────────────────────────────────────────────
function PeriodBadge({ period }: { period: StatPeriod }) {
  const p = PERIODS.find((x) => x.key === period)!;
  return (
    <span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 uppercase tracking-widest px-2 py-0.5 bg-gray-100 rounded-full border border-gray-200">
      <Calendar className="w-2.5 h-2.5" />
      {p.shortLabel}
    </span>
  );
}

// ── Admin Dashboard Page ────────────────────────────────────────────────
export default function AdminDashboardPage() {
  const router = useRouter();
  const user = useUser();
  const [period, setPeriod] = useState<StatPeriod>('month');
  const { data: stats, isLoading, isError, refetch } = useAdminStats(period);
  const activePeriod = PERIODS.find((p) => p.key === period)!;

  const statCards = [
    {
      label: 'Total Pengguna',
      sublabel: 'Semua pengguna terdaftar',
      value: stats?.total_users?.toLocaleString('id-ID') ?? '—',
      icon: <Users className="w-5 h-5" />,
      color: 'text-blue-600 bg-blue-50',
      href: '/dashboard/admin/users',
      allTime: true,
    },
    {
      label: 'Total Pesanan',
      sublabel: activePeriod.shortLabel,
      value: stats?.total_orders?.toLocaleString('id-ID') ?? '—',
      icon: <ShoppingCart className="w-5 h-5" />,
      color: 'text-green-600 bg-green-50',
      href: '/dashboard/admin/orders',
      allTime: false,
    },
    {
      label: 'Produk Aktif',
      sublabel: 'Semua produk aktif',
      value: stats?.total_products?.toLocaleString('id-ID') ?? '—',
      icon: <Package className="w-5 h-5" />,
      color: 'text-purple-600 bg-purple-50',
      href: '/dashboard/admin/products',
      allTime: true,
    },
    {
      label: 'Total Pendapatan',
      sublabel: activePeriod.shortLabel,
      value:
        stats?.total_revenue != null ? formatIDR(stats.total_revenue) : '—',
      icon: <TrendingUp className="w-5 h-5" />,
      color: 'text-amber-600 bg-amber-50',
      href: '/dashboard/admin/orders',
      allTime: false,
    },
  ];

  const recentOrders: Order[] = stats?.recent_orders ?? [];
  const chartData: RevenueChartItem[] = stats?.revenue_chart ?? [];
  const lastChartItem = chartData[chartData.length - 1];
  const prevChartItem = chartData[chartData.length - 2];
  const revenueGrowthPct = stats?.revenue_growth_pct ?? null;
  const chartRevenueGrowth =
    lastChartItem && prevChartItem && prevChartItem.revenue > 0
      ? (
          ((lastChartItem.revenue - prevChartItem.revenue) /
            prevChartItem.revenue) *
          100
        ).toFixed(1)
      : revenueGrowthPct !== null
        ? String(revenueGrowthPct)
        : null;

  return (
    <div className="max-w-7xl mx-auto">
      {/* ── Header ── */}
      <motion.div
        initial="hidden"
        animate="visible"
        variants={fadeUp}
        className="mb-6 relative"
      >
        <h1 className="text-2xl font-black text-gray-900 uppercase tracking-tight">
          Selamat datang, {user?.name?.split(' ')[0]} 👋
        </h1>
        <p className="text-gray-500 text-sm mt-1 font-medium">
          {new Date().toLocaleDateString('id-ID', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
          })}
        </p>
        <div className="absolute right-0 -top-8 w-32 md:w-48 opacity-20 pointer-events-none hidden sm:block z-0">
          <Image
            src="/mascots/saltu-cooking-pose.avif"
            alt="Saltu Mascot"
            className="w-full h-auto object-contain"
            width={500}
            height={500}
          />
        </div>
      </motion.div>

      {/* ── Period Selector Bar ── */}
      <motion.div
        initial="hidden"
        animate="visible"
        variants={fadeUp}
        custom={0.5}
        className="mb-6 flex flex-col sm:flex-row sm:items-center gap-3 p-4 bg-white/60 backdrop-blur-sm rounded-2xl border border-gray-200 shadow-sm"
      >
        <div className="flex-1">
          <p className="text-xs font-bold text-gray-900 uppercase tracking-wider">
            Periode Data
          </p>
          <p className="text-[11px] text-gray-400 font-medium mt-0.5">
            {activePeriod.desc} — semua angka di bawah mengacu pada periode ini
          </p>
        </div>
        <PeriodSelector value={period} onChange={setPeriod} />
      </motion.div>

      {/* ── Error State ── */}
      {isError && (
        <motion.div
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-6 flex items-center gap-3 px-5 py-4 bg-rose-50 border border-rose-200 rounded-2xl text-rose-700"
        >
          <AlertCircle className="w-5 h-5 shrink-0" />
          <p className="text-sm font-medium flex-1">
            Gagal memuat data statistik. Data mungkin tidak terkini.
          </p>
          <button
            onClick={() => refetch()}
            className="flex items-center gap-1.5 text-xs font-bold px-3 py-1.5 bg-rose-100 hover:bg-rose-200 rounded-lg transition-colors"
          >
            <RefreshCw className="w-3.5 h-3.5" />
            Coba Lagi
          </button>
        </motion.div>
      )}

      {/* ── Stat Cards ── */}
      <div className="mb-2 flex items-center gap-2">
        <p className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">
          Ringkasan
        </p>
        <PeriodBadge period={period} />
        {isLoading && (
          <Loader2 className="w-3 h-3 text-gray-300 animate-spin" />
        )}
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-5 mb-6">
        {isLoading
          ? Array.from({ length: 4 }).map((_, i) => (
              <StatCardSkeleton key={i} />
            ))
          : statCards.map((stat, i) => (
              <motion.div
                key={stat.label}
                initial="hidden"
                animate="visible"
                variants={fadeUp}
                custom={i + 1}
                onClick={() => router.push(stat.href)}
                className="bg-white/60 backdrop-blur-sm rounded-2xl p-5 border border-gray-200 hover:shadow-lg hover:shadow-black/5 hover:border-gray-300 transition-all relative overflow-hidden group cursor-pointer"
              >
                <div className="absolute inset-0 bg-linear-to-br from-white/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
                <div className="relative z-10">
                  <div className="flex items-center justify-between mb-4">
                    <div
                      className={`w-10 h-10 rounded-xl flex items-center justify-center ${stat.color}`}
                    >
                      {stat.icon}
                    </div>
                    <div className="flex flex-col items-end gap-1">
                      {stat.allTime ? (
                        <span className="text-[9px] font-bold text-gray-300 uppercase tracking-widest">
                          Semua Waktu
                        </span>
                      ) : (
                        <span className="text-[9px] font-bold text-yellow-500 uppercase tracking-widest">
                          {activePeriod.shortLabel}
                        </span>
                      )}
                      <ArrowRight className="w-4 h-4 text-gray-300 group-hover:text-yellow-500 group-hover:translate-x-0.5 transition-all" />
                    </div>
                  </div>
                  <AnimatePresence mode="wait">
                    <motion.p
                      key={`${stat.label}-${period}`}
                      initial={{ opacity: 0, y: 4 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -4 }}
                      className="text-2xl font-black text-gray-900 tracking-tight"
                    >
                      {stat.value}
                    </motion.p>
                  </AnimatePresence>
                  <p className="text-gray-500 text-sm mt-0.5 font-medium">
                    {stat.label}
                  </p>
                  <p className="text-[10px] text-gray-400 mt-0.5">
                    {stat.sublabel}
                  </p>
                </div>
              </motion.div>
            ))}
      </div>

      {/* ── Order Status Overview ── */}
      <div className="mb-2 flex items-center gap-2">
        <p className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">
          Status Pesanan Aktif
        </p>
        <PeriodBadge period={period} />
      </div>
      <OrderStatusOverview counts={stats?.order_status} isLoading={isLoading} />

      {/* ── Charts Row ── */}
      <div className="mb-2 flex items-center gap-2">
        <p className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">
          Grafik Historis
        </p>
        <span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 uppercase tracking-widest px-2 py-0.5 bg-gray-100 rounded-full border border-gray-200">
          <Calendar className="w-2.5 h-2.5" /> Semua Waktu
        </span>
      </div>
      <div className="grid lg:grid-cols-3 gap-5 mb-6">
        {/* Bar chart — volume pesanan */}
        {isLoading ? (
          <div className="lg:col-span-2">
            <ChartSkeleton />
          </div>
        ) : (
          <motion.div
            initial="hidden"
            animate="visible"
            variants={fadeUp}
            custom={5.5}
            className="lg:col-span-2 bg-white/60 backdrop-blur-sm rounded-2xl border border-gray-200 p-6 shadow-sm"
          >
            <div className="flex items-center justify-between mb-1">
              <h2 className="font-black text-gray-900 uppercase tracking-wide text-sm">
                Volume Pesanan
              </h2>
              <button
                onClick={() => router.push('/dashboard/admin/analytic')}
                className="flex items-center gap-1 text-xs text-yellow-600 hover:text-yellow-700 font-bold uppercase tracking-wider transition-colors"
              >
                Detail <ArrowRight className="w-3 h-3" />
              </button>
            </div>
            <p className="text-xs text-gray-400 font-medium mb-5">
              {chartData.length
                ? `${chartData.length} bulan terakhir`
                : 'Data bulanan'}
            </p>
            <MonthlyBarChart data={chartData} />
          </motion.div>
        )}

        {/* Revenue sparkline */}
        {isLoading ? (
          <ChartSkeleton />
        ) : (
          <motion.div
            initial="hidden"
            animate="visible"
            variants={fadeUp}
            custom={6}
            className="bg-white/60 backdrop-blur-sm rounded-2xl border border-gray-200 p-6 shadow-sm flex flex-col"
          >
            <h2 className="font-black text-gray-900 uppercase tracking-wide text-sm mb-1">
              Tren Pendapatan
            </h2>
            <p className="text-xs text-gray-400 font-medium mb-4">
              {chartData.length
                ? `${chartData.length} bulan terakhir`
                : 'Data bulanan'}
            </p>
            <RevenueSparkline data={chartData} />
            {lastChartItem && (
              <div className="mt-auto pt-4 border-t border-gray-100">
                <p className="text-[11px] text-gray-500 font-medium">
                  {lastChartItem
                    ? fmtPeriod(lastChartItem.period)
                    : 'Bulan ini'}
                </p>
                <p className="text-xl font-black text-gray-900 mt-0.5">
                  {formatIDR(lastChartItem.revenue)}
                </p>
                {chartRevenueGrowth !== null && (
                  <span
                    className={`text-xs font-bold ${Number(chartRevenueGrowth) >= 0 ? 'text-emerald-600' : 'text-rose-600'}`}
                  >
                    {Number(chartRevenueGrowth) >= 0 ? '↑' : '↓'}{' '}
                    {Math.abs(Number(chartRevenueGrowth))}% vs bulan lalu
                  </span>
                )}
              </div>
            )}
          </motion.div>
        )}
      </div>

      {/* ── Recent Orders ── */}
      <motion.div
        initial="hidden"
        animate="visible"
        variants={fadeUp}
        custom={7}
        className="bg-white/60 backdrop-blur-sm rounded-2xl border border-gray-200 overflow-hidden shadow-sm relative"
      >
        <div className="absolute inset-0 pointer-events-none z-0">
          <div className="absolute bottom-[-10%] right-[-5%] w-64 h-64 bg-yellow-400/5 rounded-full blur-3xl" />
        </div>

        {/* Table header */}
        <div className="px-6 py-5 border-b border-gray-200 flex items-center justify-between bg-white/40 relative z-10">
          <div>
            <div className="flex items-center gap-2 mb-0.5">
              <h2 className="font-black text-gray-900 uppercase tracking-wide">
                Pesanan Terbaru
              </h2>
              <span className="inline-flex items-center gap-1 text-[10px] font-bold text-gray-400 uppercase tracking-widest px-2 py-0.5 bg-gray-100 rounded-full border border-gray-200">
                <Calendar className="w-2.5 h-2.5" /> 10 Terakhir
              </span>
            </div>
            {stats?.total_orders != null && (
              <p className="text-xs text-gray-400 font-medium mt-0.5">
                10 terbaru · {stats.total_orders.toLocaleString('id-ID')} total
                pesanan ({activePeriod.shortLabel})
              </p>
            )}
          </div>
          <button
            onClick={() => router.push('/dashboard/admin/orders')}
            className="flex items-center gap-1.5 text-xs text-yellow-600 hover:text-yellow-700 font-bold uppercase tracking-wider transition-colors"
          >
            Lihat Semua <ArrowRight className="w-3.5 h-3.5" />
          </button>
        </div>

        <div className="overflow-x-auto relative z-10">
          {isLoading ? (
            <div className="divide-y divide-gray-100">
              {Array.from({ length: 5 }).map((_, i) => (
                <div
                  key={i}
                  className="flex items-center gap-4 px-6 py-4 animate-pulse"
                >
                  <div className="h-4 w-28 bg-gray-200 rounded" />
                  <div className="h-4 w-32 bg-gray-200 rounded flex-1" />
                  <div className="h-6 w-20 bg-gray-200 rounded-full" />
                  <div className="h-4 w-24 bg-gray-200 rounded ml-auto" />
                </div>
              ))}
            </div>
          ) : recentOrders.length === 0 ? (
            <div className="py-16 text-center">
              <div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-gray-50 border border-gray-200 mb-4">
                <ShoppingCart className="w-7 h-7 text-gray-300" />
              </div>
              <p className="text-sm font-bold text-gray-400 tracking-wide">
                Belum ada pesanan
              </p>
            </div>
          ) : (
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200 bg-white/20">
                  <th className="text-left text-[10px] font-bold text-gray-400 px-6 py-3 uppercase tracking-wider">
                    ID Pesanan
                  </th>
                  <th className="text-left text-[10px] font-bold text-gray-400 px-6 py-3 uppercase tracking-wider">
                    Status
                  </th>
                  <th className="text-right text-[10px] font-bold text-gray-400 px-6 py-3 uppercase tracking-wider">
                    Total
                  </th>
                  <th className="text-right text-[10px] font-bold text-gray-400 px-6 py-3 uppercase tracking-wider hidden lg:table-cell">
                    Tanggal
                  </th>
                  <th className="px-6 py-3 hidden sm:table-cell" />
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100/50">
                {recentOrders.map((order, i) => (
                  <motion.tr
                    key={order.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.3 + i * 0.05 }}
                    onClick={() =>
                      router.push(
                        `/dashboard/admin/orders/${order.order_number}`
                      )
                    }
                    className="hover:bg-white/60 transition-colors cursor-pointer group"
                  >
                    <td className="px-6 py-4 text-sm font-mono font-bold text-yellow-600">
                      {order.order_number}
                    </td>
                    <td className="px-6 py-4">
                      <StatusBadge status={order.status} />
                    </td>
                    <td className="px-6 py-4 text-right">
                      <span className="text-sm font-black text-gray-900">
                        {formatIDR(
                          Number(order.total) +
                            Number(order.payment?.unique_code || 0)
                        )}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right hidden lg:table-cell">
                      <span className="text-xs font-bold text-gray-400 uppercase tracking-widest">
                        {formatDate(order.created_at, {
                          day: 'numeric',
                          month: 'short',
                          year: 'numeric',
                        })}
                      </span>
                    </td>
                    <td className="px-6 py-4 hidden sm:table-cell">
                      <ArrowRight className="w-4 h-4 text-gray-300 group-hover:text-yellow-500 ml-auto transition-colors" />
                    </td>
                  </motion.tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {isLoading && (
          <div className="flex items-center justify-center gap-2 py-3 border-t border-gray-100 text-xs text-gray-400 font-medium">
            <Loader2 className="w-3.5 h-3.5 animate-spin" />
            Memuat data...
          </div>
        )}
      </motion.div>
    </div>
  );
}
