import React, { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts';
import {
  UserGroupIcon, HeartIcon, BuildingOffice2Icon, CalendarDaysIcon,
  CreditCardIcon, ArrowPathIcon, BellAlertIcon, UserPlusIcon,
  ChatBubbleLeftEllipsisIcon,
} from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { formatNumber, formatRial, formatDateTime } from '../lib/utils';

// ── Types ─────────────────────────────────────────────────────────────────

interface DashboardStats {
  total_users: number;
  active_doctors: number;
  total_doctors: number;
  total_clinics: number;
  today_appointments: number;
  total_appointments: number;
  today_payments_count: number;
  today_payments_amount: number;
  total_payments_amount: number;
  pending_comments: number;
  pending_settlements: number;
  this_month_revenue: number;
  this_month_appointments: number;
}

interface ChartData {
  appointments_30d: { date: string; count: number }[];
  revenue_30d:      { date: string; amount: number }[];
  appointment_status: { status: string; count: number }[];
  top_specialties:   { name: string; count: number }[];
}

interface RecentAppointment {
  uuid: string; slot_start: string; status: string;
  doctor_name: string; user_mobile: string; user_name: string | null; created_at: string;
}
interface RecentPayment {
  uuid: string; amount: number; status: string; gateway: string;
  user_mobile: string; user_name: string | null; created_at: string;
}
interface RecentUser {
  uuid: string; mobile: string; name: string | null; email: string | null; created_at: string;
}
interface RecentData {
  appointments: RecentAppointment[];
  payments:     RecentPayment[];
  users:        RecentUser[];
}

// ── Status maps ───────────────────────────────────────────────────────────

const APPT: Record<string, { label: string; cls: string; color: string }> = {
  waiting_for_payment: { label: 'انتظار پرداخت', cls: 'bg-yellow-100 dark:bg-yellow-400/10 text-yellow-700 dark:text-yellow-300',     color: '#f59e0b' },
  reserved:            { label: 'رزرو شده',      cls: 'bg-blue-100 dark:bg-blue-400/10 text-blue-700 dark:text-blue-300',             color: '#3b82f6' },
  checked_in:          { label: 'ورود به مطب',   cls: 'bg-indigo-100 dark:bg-indigo-400/10 text-indigo-700 dark:text-indigo-300',     color: '#6366f1' },
  waiting:             { label: 'صف انتظار',     cls: 'bg-orange-100 dark:bg-orange-400/10 text-orange-700 dark:text-orange-300',     color: '#f97316' },
  in_progress:         { label: 'در حال ویزیت',  cls: 'bg-purple-100 dark:bg-purple-400/10 text-purple-700 dark:text-purple-300',     color: '#8b5cf6' },
  visited:             { label: 'ویزیت شده',     cls: 'bg-emerald-100 dark:bg-emerald-400/10 text-emerald-700 dark:text-emerald-300', color: '#10b981' },
  completed:           { label: 'تکمیل شده',     cls: 'bg-green-100 dark:bg-green-400/10 text-green-700 dark:text-green-300',         color: '#22c55e' },
  cancelled_by_doctor: { label: 'لغو پزشک',      cls: 'bg-red-100 dark:bg-red-400/10 text-red-700 dark:text-red-300',                color: '#ef4444' },
  cancelled_by_user:   { label: 'لغو بیمار',     cls: 'bg-red-100 dark:bg-red-400/10 text-red-700 dark:text-red-300',                color: '#f43f5e' },
  auto_cancel_unpaid:  { label: 'لغو خودکار',    cls: 'bg-slate-100 dark:bg-slate-400/10 text-slate-600 dark:text-slate-400',        color: '#94a3b8' },
  no_show:             { label: 'غیبت',           cls: 'bg-slate-100 dark:bg-slate-400/10 text-slate-600 dark:text-slate-400',        color: '#64748b' },
};

const PAY: Record<string, { label: string; cls: string; color: string }> = {
  pending:  { label: 'در انتظار', cls: 'bg-yellow-100 dark:bg-yellow-400/10 text-yellow-700 dark:text-yellow-300', color: '#f59e0b' },
  received: { label: 'موفق',      cls: 'bg-green-100 dark:bg-green-400/10 text-green-700 dark:text-green-300',     color: '#22c55e' },
  canceled: { label: 'لغو شده',   cls: 'bg-red-100 dark:bg-red-400/10 text-red-700 dark:text-red-300',            color: '#ef4444' },
  refund:   { label: 'استرداد',   cls: 'bg-blue-100 dark:bg-blue-400/10 text-blue-700 dark:text-blue-300',        color: '#3b82f6' },
};

// ── Skeletons ─────────────────────────────────────────────────────────────

function KpiSkeleton() {
  return (
    <div className="cp-card p-5 flex items-start gap-4">
      <div className="w-11 h-11 rounded-xl skeleton shrink-0" />
      <div className="flex-1 space-y-2 pt-0.5">
        <div className="h-3 rounded skeleton w-2/3" />
        <div className="h-6 rounded skeleton w-1/2" />
        <div className="h-3 rounded skeleton w-3/4" />
      </div>
    </div>
  );
}

function ChartSkeleton({ h = 'h-56' }: { h?: string }) {
  return <div className={`${h} rounded-xl skeleton w-full`} />;
}

function ListSkeleton() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 4 }).map((_, i) => (
        <div key={i} className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-full skeleton shrink-0" />
          <div className="flex-1 space-y-1.5">
            <div className="h-3 rounded skeleton w-3/4" />
            <div className="h-3 rounded skeleton w-1/2" />
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Badge ─────────────────────────────────────────────────────────────────

function Badge({ status, map }: { status: string; map: Record<string, { label: string; cls: string }> }) {
  const s = map[status] ?? { label: status, cls: 'bg-slate-100 dark:bg-slate-400/10 text-slate-600' };
  return (
    <span className={`shrink-0 text-[10px] font-medium px-2 py-0.5 rounded-full ${s.cls}`}>{s.label}</span>
  );
}

// ── Chart helpers ─────────────────────────────────────────────────────────

const RADIAN = Math.PI / 180;

function PieLabelInside({ cx, cy, midAngle, innerRadius, outerRadius, percent }: {
  cx: number; cy: number; midAngle: number; innerRadius: number; outerRadius: number; percent: number;
}) {
  if (percent < 0.06) return null;
  const r = innerRadius + (outerRadius - innerRadius) * 0.5;
  const x = cx + r * Math.cos(-midAngle * RADIAN);
  const y = cy + r * Math.sin(-midAngle * RADIAN);
  return (
    <text x={x} y={y} fill="white" textAnchor="middle" dominantBaseline="central" fontSize={10} fontWeight="600">
      {`${(percent * 100).toFixed(0)}٪`}
    </text>
  );
}

function TipBox({ children }: { children: React.ReactNode }) {
  return (
    <div
      className="bg-white dark:bg-gray-800 rounded-xl border border-slate-200 dark:border-gray-700 shadow-lg px-3 py-2 text-sm"
      dir="rtl"
    >
      {children}
    </div>
  );
}

function ApptTooltip({ active, payload, label }: { active?: boolean; payload?: { value: number }[]; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <TipBox>
      <p className="text-xs text-slate-500 dark:text-slate-400 mb-0.5">{label}</p>
      <p className="font-bold text-violet-600 dark:text-violet-400">{formatNumber(payload[0]?.value ?? 0)} نوبت</p>
    </TipBox>
  );
}

function RevTooltip({ active, payload, label }: { active?: boolean; payload?: { value: number }[]; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <TipBox>
      <p className="text-xs text-slate-500 dark:text-slate-400 mb-0.5">{label}</p>
      <p className="font-bold text-pink-600 dark:text-pink-400">{formatRial(payload[0]?.value ?? 0)}</p>
    </TipBox>
  );
}

function BarTip({ active, payload, label }: { active?: boolean; payload?: { value: number }[]; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <TipBox>
      <p className="font-medium text-slate-700 dark:text-slate-200 mb-0.5">{label}</p>
      <p className="font-bold text-violet-600 dark:text-violet-400">{formatNumber(payload[0]?.value ?? 0)} نوبت</p>
    </TipBox>
  );
}

const revAxisFmt = (v: number) =>
  v >= 1_000_000_000 ? `${(v / 1_000_000_000).toFixed(1)}B`
  : v >= 1_000_000  ? `${(v / 1_000_000).toFixed(0)}M`
  : v >= 1_000      ? `${Math.round(v / 1_000)}K`
  : String(v);

// ── Main Component ────────────────────────────────────────────────────────

export default function DashboardPage() {
  const [chartTab, setChartTab] = useState<'appointments' | 'revenue'>('appointments');

  const statsQ = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: () => api.get<ApiResponse<DashboardStats>>('/api/v1/admin/dashboard/stats'),
    staleTime: 60_000,
  });
  const chartsQ = useQuery({
    queryKey: ['dashboard-charts'],
    queryFn: () => api.get<ApiResponse<ChartData>>('/api/v1/admin/dashboard/charts'),
    staleTime: 120_000,
  });
  const recentQ = useQuery({
    queryKey: ['dashboard-recent'],
    queryFn: () => api.get<ApiResponse<RecentData>>('/api/v1/admin/dashboard/recent'),
    staleTime: 30_000,
  });

  const stats  = useMemo<DashboardStats | undefined>(() => (statsQ.data?.data  as any)?.data ?? statsQ.data?.data,  [statsQ.data]);
  const charts = useMemo<ChartData | undefined>(     () => (chartsQ.data?.data as any)?.data ?? chartsQ.data?.data, [chartsQ.data]);
  const recent = useMemo<RecentData | undefined>(    () => (recentQ.data?.data as any)?.data ?? recentQ.data?.data, [recentQ.data]);

  const fn = (n?: number) => n !== undefined ? formatNumber(n) : '—';
  const fr = (n?: number) => n !== undefined ? formatRial(n) : '—';
  const today = new Date().toLocaleDateString('fa-IR', { year: 'numeric', month: 'long', day: 'numeric' });

  // KPI cards
  const kpiCards = [
    { label: 'کل کاربران',      value: fn(stats?.total_users),          sub: undefined,                                                              icon: UserGroupIcon,            iconBg: 'bg-violet-100 dark:bg-violet-400/10', iconColor: 'text-violet-600 dark:text-violet-400' },
    { label: 'پزشکان فعال',     value: fn(stats?.active_doctors),       sub: stats ? `از ${fn(stats.total_doctors)} پزشک` : undefined,              icon: HeartIcon,                iconBg: 'bg-emerald-100 dark:bg-emerald-400/10', iconColor: 'text-emerald-600 dark:text-emerald-400' },
    { label: 'کلینیک‌ها',       value: fn(stats?.total_clinics),        sub: undefined,                                                              icon: BuildingOffice2Icon,      iconBg: 'bg-blue-100 dark:bg-blue-400/10', iconColor: 'text-blue-600 dark:text-blue-400' },
    { label: 'نوبت‌های امروز',  value: fn(stats?.today_appointments),   sub: stats ? `ماه جاری: ${fn(stats.this_month_appointments)}` : undefined,  icon: CalendarDaysIcon,         iconBg: 'bg-orange-100 dark:bg-orange-400/10', iconColor: 'text-orange-600 dark:text-orange-400' },
    { label: 'درآمد این ماه',   value: fr(stats?.this_month_revenue),   sub: stats ? `کل: ${fr(stats.total_payments_amount)}` : undefined,          icon: CreditCardIcon,           iconBg: 'bg-pink-100 dark:bg-pink-400/10', iconColor: 'text-pink-600 dark:text-pink-400' },
    { label: 'در انتظار بررسی', value: fn(stats ? stats.pending_comments + stats.pending_settlements : undefined), sub: stats ? `${fn(stats.pending_comments)} نظر · ${fn(stats.pending_settlements)} تسویه` : undefined, icon: BellAlertIcon, iconBg: 'bg-amber-100 dark:bg-amber-400/10', iconColor: 'text-amber-600 dark:text-amber-400' },
  ];

  // Activity timeline
  const timelineEvents = useMemo(() => {
    if (!recent) return [];
    const evs: { title: string; sub?: string; time: string; color: string }[] = [];
    (recent.appointments ?? []).slice(0, 4).forEach((a) => {
      evs.push({ title: `نوبت ${APPT[a.status]?.label ?? a.status}`, sub: `${a.user_name || a.user_mobile} · دکتر ${a.doctor_name}`, time: a.created_at, color: APPT[a.status]?.color ?? '#94a3b8' });
    });
    (recent.payments ?? []).slice(0, 3).forEach((p) => {
      evs.push({ title: `پرداخت ${PAY[p.status]?.label ?? p.status}`, sub: `${p.user_name || p.user_mobile} · ${formatRial(p.amount)}`, time: p.created_at, color: PAY[p.status]?.color ?? '#94a3b8' });
    });
    (recent.users ?? []).slice(0, 3).forEach((u) => {
      evs.push({ title: 'ثبت‌نام کاربر جدید', sub: u.name || u.mobile, time: u.created_at, color: '#8b5cf6' });
    });
    return evs.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime()).slice(0, 10);
  }, [recent]);

  // Quick actions
  const quickActions = [
    { label: 'پزشکان',    to: '/admin/doctors',      icon: HeartIcon,                 iconBg: 'bg-emerald-100 dark:bg-emerald-400/10', iconColor: 'text-emerald-600 dark:text-emerald-400' },
    { label: 'کلینیک‌ها', to: '/admin/clinics',      icon: BuildingOffice2Icon,       iconBg: 'bg-blue-100 dark:bg-blue-400/10',       iconColor: 'text-blue-600 dark:text-blue-400' },
    { label: 'نوبت‌ها',   to: '/admin/appointments', icon: CalendarDaysIcon,          iconBg: 'bg-orange-100 dark:bg-orange-400/10',   iconColor: 'text-orange-600 dark:text-orange-400' },
    { label: 'پرداخت‌ها', to: '/admin/payments',     icon: CreditCardIcon,            iconBg: 'bg-pink-100 dark:bg-pink-400/10',       iconColor: 'text-pink-600 dark:text-pink-400' },
    { label: 'کاربران',   to: '/admin/users',        icon: UserGroupIcon,             iconBg: 'bg-violet-100 dark:bg-violet-400/10',   iconColor: 'text-violet-600 dark:text-violet-400' },
    { label: 'نظرات',     to: '/admin/comments',     icon: ChatBubbleLeftEllipsisIcon, iconBg: 'bg-amber-100 dark:bg-amber-400/10',    iconColor: 'text-amber-600 dark:text-amber-400' },
  ];

  const isFetching = statsQ.isFetching || chartsQ.isFetching || recentQ.isFetching;

  return (
    <div className="animate-slide-up space-y-5">

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold text-slate-900 dark:text-slate-50">داشبورد</h1>
          <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">{today}</p>
        </div>
        <button
          onClick={() => { statsQ.refetch(); chartsQ.refetch(); recentQ.refetch(); }}
          disabled={isFetching}
          className="flex items-center gap-1.5 text-sm text-slate-500 dark:text-slate-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors disabled:opacity-50"
        >
          <ArrowPathIcon className={`w-4 h-4 ${isFetching ? 'animate-spin' : ''}`} />
          به‌روزرسانی
        </button>
      </div>

      {/* ── Section 1: KPI Cards ─────────────────────────────────── */}
      <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-6 gap-3">
        {statsQ.isLoading
          ? Array.from({ length: 6 }).map((_, i) => <KpiSkeleton key={i} />)
          : kpiCards.map((c) => (
            <div key={c.label} className="cp-card p-4 flex items-start gap-3">
              <div className={`cp-stat-icon ${c.iconBg} shrink-0`}>
                <c.icon className={`w-5 h-5 ${c.iconColor}`} />
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1 truncate">{c.label}</p>
                <p className="text-lg font-bold text-slate-900 dark:text-slate-50 leading-none">{c.value}</p>
                {c.sub && <p className="text-[11px] text-slate-400 dark:text-slate-500 mt-1.5 leading-tight">{c.sub}</p>}
              </div>
            </div>
          ))
        }
      </div>

      {/* ── Section 2: Charts ───────────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">

        {/* Trend chart with tab toggle */}
        <div className="cp-card p-5 lg:col-span-2">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">
              {chartTab === 'appointments' ? 'نوبت‌ها — ۳۰ روز اخیر' : 'درآمد — ۳۰ روز اخیر'}
            </h3>
            <div className="flex gap-0.5 bg-slate-100 dark:bg-gray-800 rounded-lg p-0.5">
              {(['appointments', 'revenue'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setChartTab(tab)}
                  className={`text-xs px-3 py-1 rounded-md transition-all ${
                    chartTab === tab
                      ? 'bg-white dark:bg-gray-700 text-slate-800 dark:text-slate-200 shadow-sm font-medium'
                      : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
                  }`}
                >
                  {tab === 'appointments' ? 'نوبت‌ها' : 'درآمد'}
                </button>
              ))}
            </div>
          </div>
          {chartsQ.isLoading ? <ChartSkeleton h="h-52" /> : (
            <div dir="ltr" className="w-full h-52">
              <ResponsiveContainer width="100%" height="100%">
                {chartTab === 'appointments' ? (
                  <AreaChart data={charts?.appointments_30d ?? []} margin={{ top: 4, right: 4, left: -16, bottom: 0 }}>
                    <defs>
                      <linearGradient id="apptGrad" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%"  stopColor="#8b5cf6" stopOpacity={0.25} />
                        <stop offset="95%" stopColor="#8b5cf6" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.6} />
                    <XAxis dataKey="date" tick={{ fontSize: 10, fill: '#94a3b8' }} interval={4} tickLine={false} axisLine={false} />
                    <YAxis tick={{ fontSize: 10, fill: '#94a3b8' }} tickLine={false} axisLine={false} />
                    <Tooltip content={<ApptTooltip />} cursor={{ stroke: '#8b5cf6', strokeWidth: 1, strokeDasharray: '4 4' }} />
                    <Area type="monotone" dataKey="count" stroke="#8b5cf6" strokeWidth={2.5} fill="url(#apptGrad)" dot={false} activeDot={{ r: 4, fill: '#8b5cf6', strokeWidth: 0 }} />
                  </AreaChart>
                ) : (
                  <AreaChart data={charts?.revenue_30d ?? []} margin={{ top: 4, right: 4, left: -4, bottom: 0 }}>
                    <defs>
                      <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%"  stopColor="#ec4899" stopOpacity={0.25} />
                        <stop offset="95%" stopColor="#ec4899" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.6} />
                    <XAxis dataKey="date" tick={{ fontSize: 10, fill: '#94a3b8' }} interval={4} tickLine={false} axisLine={false} />
                    <YAxis tick={{ fontSize: 10, fill: '#94a3b8' }} tickLine={false} axisLine={false} tickFormatter={revAxisFmt} />
                    <Tooltip content={<RevTooltip />} cursor={{ stroke: '#ec4899', strokeWidth: 1, strokeDasharray: '4 4' }} />
                    <Area type="monotone" dataKey="amount" stroke="#ec4899" strokeWidth={2.5} fill="url(#revGrad)" dot={false} activeDot={{ r: 4, fill: '#ec4899', strokeWidth: 0 }} />
                  </AreaChart>
                )}
              </ResponsiveContainer>
            </div>
          )}
        </div>

        {/* Donut chart — appointment status */}
        <div className="cp-card p-5">
          <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200 mb-4">وضعیت نوبت‌ها</h3>
          {chartsQ.isLoading ? <ChartSkeleton h="h-40" /> : (
            <div dir="ltr" className="w-full h-40">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={charts?.appointment_status?.slice(0, 7) ?? []}
                    dataKey="count"
                    nameKey="status"
                    cx="50%" cy="50%"
                    innerRadius={42} outerRadius={68}
                    labelLine={false}
                    label={PieLabelInside as any}
                  >
                    {(charts?.appointment_status?.slice(0, 7) ?? []).map((entry: { status: string }) => (
                      <Cell key={entry.status} fill={APPT[entry.status]?.color ?? '#94a3b8'} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value, name) => [formatNumber(Number(value)), APPT[String(name)]?.label ?? String(name)]}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          )}
          {!chartsQ.isLoading && (
            <ul className="mt-3 space-y-1.5">
              {(charts?.appointment_status ?? []).slice(0, 5).map((s: { status: string; count: number }) => (
                <li key={s.status} className="flex items-center justify-between">
                  <div className="flex items-center gap-1.5">
                    <span className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: APPT[s.status]?.color ?? '#94a3b8' }} />
                    <span className="text-xs text-slate-600 dark:text-slate-400">{APPT[s.status]?.label ?? s.status}</span>
                  </div>
                  <span className="text-xs font-semibold text-slate-800 dark:text-slate-200">{formatNumber(s.count)}</span>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      {/* ── Section 3: Top Specialties Bar Chart ─────────────────── */}
      <div className="cp-card p-5">
        <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200 mb-4">پرتکرارترین تخصص‌ها</h3>
        {chartsQ.isLoading ? <ChartSkeleton h="h-64" /> : !charts?.top_specialties?.length ? (
          <p className="text-center py-10 text-sm text-slate-400 dark:text-slate-500">داده‌ای موجود نیست</p>
        ) : (
          <div dir="ltr" className="w-full h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={charts.top_specialties}
                layout="vertical"
                margin={{ top: 0, right: 16, left: 0, bottom: 0 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.6} horizontal={false} />
                <XAxis type="number" tick={{ fontSize: 10, fill: '#94a3b8' }} tickLine={false} axisLine={false} />
                <YAxis type="category" dataKey="name" width={140} tick={{ fontSize: 11, fill: '#64748b' }} tickLine={false} axisLine={false} />
                <Tooltip content={<BarTip />} cursor={{ fill: 'rgba(139,92,246,0.08)' }} />
                <Bar dataKey="count" fill="#8b5cf6" radius={[0, 5, 5, 0]} maxBarSize={22} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        )}
      </div>

      {/* ── Sections 4 & 5: Quick Actions + Activity Timeline ─────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">

        {/* Quick actions */}
        <div className="cp-card p-5">
          <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200 mb-4">دسترسی سریع</h3>
          <div className="grid grid-cols-2 gap-2">
            {quickActions.map((a) => (
              <Link
                key={a.to}
                to={a.to}
                className="flex flex-col items-center gap-2 p-3 rounded-xl hover:bg-slate-50 dark:hover:bg-gray-800 border border-transparent hover:border-slate-200 dark:hover:border-gray-700 transition-all group"
              >
                <div className={`w-10 h-10 rounded-xl ${a.iconBg} flex items-center justify-center`}>
                  <a.icon className={`w-5 h-5 ${a.iconColor}`} />
                </div>
                <span className="text-xs font-medium text-slate-700 dark:text-slate-300 text-center group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                  {a.label}
                </span>
              </Link>
            ))}
          </div>
        </div>

        {/* Activity timeline */}
        <div className="cp-card p-5 lg:col-span-2">
          <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200 mb-4">آخرین رویدادها</h3>
          {recentQ.isLoading ? (
            <div className="space-y-4">
              {Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="flex gap-3">
                  <div className="flex flex-col items-center">
                    <div className="w-2.5 h-2.5 rounded-full skeleton mt-1 shrink-0" />
                    {i < 5 && <div className="w-px h-8 skeleton mt-1.5" />}
                  </div>
                  <div className="flex-1 pb-4 space-y-1.5">
                    <div className="h-3 rounded skeleton w-3/4" />
                    <div className="h-3 rounded skeleton w-1/2" />
                  </div>
                </div>
              ))}
            </div>
          ) : !timelineEvents.length ? (
            <p className="text-center py-8 text-sm text-slate-400 dark:text-slate-500">رویدادی ثبت نشده</p>
          ) : (
            <div>
              {timelineEvents.map((ev, i) => (
                <div key={i} className="flex gap-3">
                  <div className="flex flex-col items-center">
                    <div
                      className="w-2.5 h-2.5 rounded-full shrink-0 mt-1.5 ring-2 ring-white dark:ring-gray-900"
                      style={{ backgroundColor: ev.color }}
                    />
                    {i < timelineEvents.length - 1 && (
                      <div className="w-px flex-1 bg-slate-200 dark:bg-gray-700 mt-1 mb-1" />
                    )}
                  </div>
                  <div className={`flex-1 min-w-0 ${i < timelineEvents.length - 1 ? 'pb-3.5' : ''}`}>
                    <p className="text-sm font-medium text-slate-800 dark:text-slate-200">{ev.title}</p>
                    {ev.sub && <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5 truncate">{ev.sub}</p>}
                    <p className="text-[11px] text-slate-400 dark:text-slate-500 mt-0.5">{formatDateTime(ev.time)}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* ── Section 6: Recent Data ───────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">

        {/* Recent appointments */}
        <div className="cp-card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">آخرین نوبت‌ها</h3>
            <Link to="/admin/appointments" className="text-xs text-primary-600 dark:text-primary-400 hover:underline">همه</Link>
          </div>
          {recentQ.isLoading ? <ListSkeleton /> : !recent?.appointments?.length ? (
            <p className="text-center py-6 text-sm text-slate-400 dark:text-slate-500">نوبتی ثبت نشده</p>
          ) : (
            <ul className="space-y-3">
              {recent.appointments.map((a) => (
                <li key={a.uuid}>
                  <Link to={`/admin/appointments/${a.uuid}`} className="flex items-start justify-between gap-2 group">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        {a.user_name || a.user_mobile}
                      </p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 truncate">دکتر {a.doctor_name}</p>
                      <p className="text-[11px] text-slate-400 dark:text-slate-500 mt-0.5">{formatDateTime(a.slot_start)}</p>
                    </div>
                    <Badge status={a.status} map={APPT} />
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>

        {/* Recent payments */}
        <div className="cp-card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">آخرین پرداخت‌ها</h3>
            <Link to="/admin/payments" className="text-xs text-primary-600 dark:text-primary-400 hover:underline">همه</Link>
          </div>
          {recentQ.isLoading ? <ListSkeleton /> : !recent?.payments?.length ? (
            <p className="text-center py-6 text-sm text-slate-400 dark:text-slate-500">پرداختی ثبت نشده</p>
          ) : (
            <ul className="space-y-3">
              {recent.payments.map((p) => (
                <li key={p.uuid}>
                  <Link to={`/admin/payments/${p.uuid}`} className="flex items-start justify-between gap-2 group">
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        {p.user_name || p.user_mobile}
                      </p>
                      <p className="text-xs text-slate-500 dark:text-slate-400">{formatRial(p.amount)}</p>
                      <p className="text-[11px] text-slate-400 dark:text-slate-500 mt-0.5">{formatDateTime(p.created_at)}</p>
                    </div>
                    <Badge status={p.status} map={PAY} />
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>

        {/* Recent users */}
        <div className="cp-card p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-200">کاربران جدید</h3>
            <Link to="/admin/users" className="text-xs text-primary-600 dark:text-primary-400 hover:underline">همه</Link>
          </div>
          {recentQ.isLoading ? <ListSkeleton /> : !recent?.users?.length ? (
            <p className="text-center py-6 text-sm text-slate-400 dark:text-slate-500">کاربری ثبت نشده</p>
          ) : (
            <ul className="space-y-3">
              {recent.users.map((u) => (
                <li key={u.uuid}>
                  <Link to={`/admin/users/${u.uuid}`} className="flex items-center gap-3 group">
                    <div className="w-8 h-8 rounded-full bg-violet-100 dark:bg-violet-400/10 flex items-center justify-center shrink-0">
                      <UserPlusIcon className="w-4 h-4 text-violet-600 dark:text-violet-400" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-slate-800 dark:text-slate-200 truncate group-hover:text-primary-600 dark:group-hover:text-primary-400 transition-colors">
                        {u.name || u.mobile}
                      </p>
                      {u.name && <p className="text-xs text-slate-500 dark:text-slate-400 truncate" dir="ltr">{u.mobile}</p>}
                      <p className="text-[11px] text-slate-400 dark:text-slate-500">{formatDateTime(u.created_at)}</p>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

    </div>
  );
}
