import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
  LineChart, Line, BarChart, Bar, PieChart, Pie, Cell, Legend,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts'
import { getDashboardKPIs } from '../../api/analytics'

const SCHAEFFLER_GREEN = '#00893d'
const INDIGO = '#6366f1'
const AMBER = '#f59e0b'
const GREEN = '#22c55e'
const RED = '#ef4444'
const BLUE = '#3b82f6'
const PURPLE = '#8b5cf6'
const TEAL = '#14b8a6'
const ROSE = '#f43f5e'
const CYAN = '#06b6d4'

const CATEGORY_COLORS = [SCHAEFFLER_GREEN, INDIGO, AMBER, BLUE, PURPLE, TEAL, ROSE, CYAN]

const CHART_TOOLTIP_STYLE = {
  backgroundColor: 'var(--color-bg-surface)',
  border: '1px solid var(--color-border)',
  borderRadius: '8px',
  color: 'var(--color-text)',
}

type Preset = '4w' | '3m' | '6m' | '1y' | 'all' | 'custom'

const PRESETS: { key: Preset; label: string }[] = [
  { key: '4w', label: '4 W' },
  { key: '3m', label: '3 M' },
  { key: '6m', label: '6 M' },
  { key: '1y', label: '1 Y' },
  { key: 'all', label: 'All' },
  { key: 'custom', label: 'Custom' },
]

function toISO(d: Date): string {
  return d.toISOString().slice(0, 10)
}

function presetRange(key: Preset): { from: string; to: string } | null {
  const now = new Date()
  const to = toISO(now)
  switch (key) {
    case '4w': { const d = new Date(now); d.setDate(d.getDate() - 28); return { from: toISO(d), to } }
    case '3m': { const d = new Date(now); d.setMonth(d.getMonth() - 3); return { from: toISO(d), to } }
    case '6m': { const d = new Date(now); d.setMonth(d.getMonth() - 6); return { from: toISO(d), to } }
    case '1y': { const d = new Date(now); d.setFullYear(d.getFullYear() - 1); return { from: toISO(d), to } }
    case 'all': return null // no params → backend defaults omitted, we send nothing
    case 'custom': return null
  }
}

function presetSubtitle(key: Preset, customFrom: string, customTo: string): string {
  switch (key) {
    case '4w': return 'Last 4 weeks'
    case '3m': return 'Last 3 months'
    case '6m': return 'Last 6 months'
    case '1y': return 'Last year'
    case 'all': return 'All time'
    case 'custom': {
      if (customFrom && customTo) {
        const f = new Date(customFrom + 'T00:00:00')
        const t = new Date(customTo + 'T00:00:00')
        const fmt = (d: Date) => d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
        return `${fmt(f)} – ${fmt(t)}`
      }
      return 'Select a date range'
    }
  }
}

function fmtSeconds(s: number | null | undefined): string {
  if (s == null) return '—'
  if (s >= 60) return `${(s / 60).toFixed(1)} min`
  return `${s.toFixed(1)} s`
}

export default function AdminDashboard() {
  const [preset, setPreset] = useState<Preset>('6m')
  const [customFrom, setCustomFrom] = useState('')
  const [customTo, setCustomTo] = useState('')

  const { dateFrom, dateTo } = useMemo(() => {
    if (preset === 'custom') {
      return { dateFrom: customFrom || undefined, dateTo: customTo || undefined }
    }
    if (preset === 'all') {
      return { dateFrom: '2000-01-01', dateTo: toISO(new Date()) }
    }
    const range = presetRange(preset)
    return range ? { dateFrom: range.from, dateTo: range.to } : { dateFrom: undefined, dateTo: undefined }
  }, [preset, customFrom, customTo])

  const { data, isLoading, error } = useQuery({
    queryKey: ['dashboard-kpis', dateFrom, dateTo],
    queryFn: () => getDashboardKPIs(dateFrom, dateTo),
    staleTime: 60_000,
  })

  function selectPreset(key: Preset) {
    setPreset(key)
    if (key !== 'custom') {
      setCustomFrom('')
      setCustomTo('')
    }
  }

  const subtitle = presetSubtitle(preset, customFrom, customTo)

  if (isLoading) return <div className="p-8 text-center text-content-muted">Loading analytics…</div>
  if (error) return <div className="p-8 text-center text-red-500">Failed to load analytics</div>
  if (!data) return null

  const {
    summary, throughput, revenue, processing_times, item_status, render_times,
    product_stats, output_type_usage, render_status, renderer_usage,
    top_products, orders_by_user, category_revenue, render_backend_stats,
    render_time_by_output_type,
  } = data

  const pieData = [
    { name: 'Pending', value: item_status.pending, color: AMBER },
    { name: 'Approved', value: item_status.approved, color: GREEN },
    { name: 'Rejected', value: item_status.rejected, color: RED },
  ]

  const renderStatusPieData = [
    { name: 'Pending', value: render_status.pending, color: AMBER },
    { name: 'Processing', value: render_status.processing, color: BLUE },
    { name: 'Completed', value: render_status.completed, color: GREEN },
    { name: 'Failed', value: render_status.failed, color: RED },
  ]

  const rendererPieData = renderer_usage.map((r, i) => ({
    name: r.renderer || 'unknown',
    value: r.count,
    color: CATEGORY_COLORS[i % CATEGORY_COLORS.length],
  }))

  return (
    <div className="p-8 space-y-6">
      <div className="mb-2">
        <h1 className="text-2xl font-bold text-content">Analytics Dashboard</h1>
        <p className="text-content-muted mt-1 text-sm">{subtitle} · refreshes every 60 s</p>
      </div>

      {/* Timeframe selector bar */}
      <div className="flex flex-wrap items-center gap-2">
        {PRESETS.map(({ key, label }) => (
          <button
            key={key}
            onClick={() => selectPreset(key)}
            className={`px-3 py-1.5 rounded-full text-xs font-semibold transition-colors ${
              preset === key
                ? 'text-white'
                : 'bg-surface-muted text-content-secondary hover:bg-surface-hover'
            }`}
            style={preset === key ? { backgroundColor: 'var(--color-accent)' } : undefined}
          >
            {label}
          </button>
        ))}

        {preset === 'custom' && (
          <div className="flex items-center gap-2 ml-2">
            <input
              type="date"
              value={customFrom}
              onChange={(e) => setCustomFrom(e.target.value)}
              className="border border-border-default rounded px-2 py-1 text-xs"
            />
            <span className="text-content-muted text-xs">–</span>
            <input
              type="date"
              value={customTo}
              onChange={(e) => setCustomTo(e.target.value)}
              className="border border-border-default rounded px-2 py-1 text-xs"
            />
          </div>
        )}
      </div>

      {/* Row 1 — Summary cards */}
      <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
        <SummaryCard label="Total Orders" value={summary.total_orders} />
        <SummaryCard label="Completed" value={summary.completed_orders} />
        <SummaryCard label="Rendering Items" value={summary.total_rendering_items} />
        <SummaryCard label="Total Revenue (€)" value={`€ ${summary.total_revenue.toFixed(2)}`} />
        <SummaryCard label="Products Rendered" value={product_stats.unique_products_rendered} />
        <SummaryCard label="CAD Coverage" value={`${product_stats.products_with_cad} / ${product_stats.total_products}`} />
      </div>

      {/* Row 2 — Throughput + Item status */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="card p-4 lg:col-span-2">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Order Throughput (weekly)</h2>
          {throughput.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <LineChart data={throughput} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="week" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} allowDecimals={false} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Line type="monotone" dataKey="count" name="Created" stroke={SCHAEFFLER_GREEN} strokeWidth={2} dot={false} />
                <Line type="monotone" dataKey="completed" name="Completed" stroke={INDIGO} strokeWidth={2} dot={false} />
              </LineChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Item Status</h2>
          {pieData.every((d) => d.value === 0) ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <PieChart>
                <Pie
                  data={pieData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="45%"
                  outerRadius={70}
                  label={({ name, value }) => `${name}: ${value}`}
                  labelLine={false}
                >
                  {pieData.map((entry) => (
                    <Cell key={entry.name} fill={entry.color} />
                  ))}
                </Pie>
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* Row 3 — Revenue + Processing times */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Revenue per Month (€)</h2>
          {revenue.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={revenue} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="month" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} formatter={(v: number | undefined) => v != null ? [`€ ${v.toFixed(2)}`, 'Revenue'] : ['—', 'Revenue']} />
                <Bar dataKey="revenue" fill={SCHAEFFLER_GREEN} radius={[3, 3, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-4">Processing Times</h2>
          <table className="w-full text-sm">
            <tbody className="divide-y divide-border-light">
              <MetricRow label="Avg submit → complete" value={fmtSeconds(processing_times.avg_submit_to_complete_s)} />
              <MetricRow label="Avg submit → processing" value={fmtSeconds(processing_times.avg_submit_to_processing_s)} />
              <MetricRow label="P50 (median)" value={fmtSeconds(processing_times.p50_s)} />
              <MetricRow label="P95" value={fmtSeconds(processing_times.p95_s)} />
            </tbody>
          </table>

          <h2 className="text-sm font-semibold text-content-secondary mt-5 mb-3">Render Time Breakdown</h2>
          <table className="w-full text-sm">
            <tbody className="divide-y divide-border-light">
              <MetricRow label="Avg render time" value={fmtSeconds(render_times.avg_render_s)} />
              <MetricRow label="Completed renders" value={String(render_times.sample_count)} />
            </tbody>
          </table>
        </div>
      </div>

      {/* Row 3b — Render Time by Output Type */}
      {render_time_by_output_type && render_time_by_output_type.length > 0 && (
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-4">Renderzeit pro Output-Typ</h2>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Horizontal bar chart: Avg + P50 per output type */}
            <ResponsiveContainer width="100%" height={Math.max(180, render_time_by_output_type.length * 44)}>
              <BarChart
                data={render_time_by_output_type}
                layout="vertical"
                margin={{ top: 4, right: 40, left: 8, bottom: 4 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" horizontal={false} />
                <XAxis
                  type="number"
                  tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }}
                  tickFormatter={(v: number) => v >= 60 ? `${(v / 60).toFixed(0)}m` : `${v.toFixed(0)}s`}
                />
                <YAxis type="category" dataKey="output_type" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} width={130} />
                <Tooltip
                  contentStyle={CHART_TOOLTIP_STYLE}
                  formatter={(v: number | null | undefined, name: string) => [
                    v != null ? (v >= 60 ? `${(v / 60).toFixed(1)} min` : `${v.toFixed(0)} s`) : '—',
                    name,
                  ]}
                />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Bar dataKey="avg_render_s" name="Ø Renderzeit" fill={INDIGO} radius={[0, 3, 3, 0]} />
                <Bar dataKey="p50_render_s" name="Median (P50)" fill={TEAL} radius={[0, 3, 3, 0]} />
              </BarChart>
            </ResponsiveContainer>

            {/* Detail table */}
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr className="border-b border-border-default text-left text-content-muted">
                    <th className="pb-2 pr-3 font-medium">Output-Typ</th>
                    <th className="pb-2 px-2 font-medium text-right">Jobs</th>
                    <th className="pb-2 px-2 font-medium text-right">Ø</th>
                    <th className="pb-2 px-2 font-medium text-right">P50</th>
                    <th className="pb-2 px-2 font-medium text-right">Min</th>
                    <th className="pb-2 pl-2 font-medium text-right">Max</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border-light">
                  {render_time_by_output_type.map((r) => (
                    <tr key={r.output_type} className="hover:bg-surface-hover">
                      <td className="py-1.5 pr-3 font-medium text-content-secondary max-w-[160px] truncate" title={r.output_type}>
                        {r.output_type}
                      </td>
                      <td className="py-1.5 px-2 text-right text-content-muted">{r.job_count}</td>
                      <td className="py-1.5 px-2 text-right tabular-nums">{fmtSeconds(r.avg_render_s)}</td>
                      <td className="py-1.5 px-2 text-right tabular-nums text-content-muted">{fmtSeconds(r.p50_render_s)}</td>
                      <td className="py-1.5 px-2 text-right tabular-nums text-content-muted">{fmtSeconds(r.min_render_s)}</td>
                      <td className="py-1.5 pl-2 text-right tabular-nums text-content-muted">{fmtSeconds(r.max_render_s)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* Row 4 — Output Type Usage + Render Status */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Output Type Usage</h2>
          {output_type_usage.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={output_type_usage} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="output_type" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} allowDecimals={false} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
                <Bar dataKey="count" fill={INDIGO} radius={[3, 3, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Render Status</h2>
          {renderStatusPieData.every((d) => d.value === 0) ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <PieChart>
                <Pie
                  data={renderStatusPieData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="45%"
                  outerRadius={70}
                  label={({ name, value }) => `${name}: ${value}`}
                  labelLine={false}
                >
                  {renderStatusPieData.map((entry) => (
                    <Cell key={entry.name} fill={entry.color} />
                  ))}
                </Pie>
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* Row 5 — Products by Category + Renderer Usage */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Products by Category</h2>
          {product_stats.products_by_category.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={product_stats.products_by_category} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="category" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} allowDecimals={false} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
                <Bar dataKey="count" radius={[3, 3, 0, 0]}>
                  {product_stats.products_by_category.map((_, i) => (
                    <Cell key={i} fill={CATEGORY_COLORS[i % CATEGORY_COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Renderer Usage</h2>
          {rendererPieData.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <PieChart>
                <Pie
                  data={rendererPieData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="45%"
                  outerRadius={70}
                  label={({ name, value }) => `${name}: ${value}`}
                  labelLine={false}
                >
                  {rendererPieData.map((entry) => (
                    <Cell key={entry.name} fill={entry.color} />
                  ))}
                </Pie>
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* Row 5b — Render Backend Comparison */}
      {render_backend_stats.length > 0 && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          <div className="card p-4">
            <h2 className="text-sm font-semibold text-content-secondary mb-3">Render Backend — Job Count</h2>
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={render_backend_stats} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="backend" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} allowDecimals={false} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Bar dataKey="completed" name="Completed" fill={GREEN} radius={[3, 3, 0, 0]} />
                <Bar dataKey="failed" name="Failed" fill={RED} radius={[3, 3, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>

          <div className="card p-4">
            <h2 className="text-sm font-semibold text-content-secondary mb-3">Render Backend — Avg Time</h2>
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={render_backend_stats} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="backend" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} label={{ value: 'seconds', angle: -90, position: 'insideLeft', style: { fontSize: 10 } }} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} formatter={(v: number | undefined) => v != null ? [`${v.toFixed(1)}s`, ''] : ['—', '']} />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Bar dataKey="avg_render_s" name="Avg" fill={INDIGO} radius={[3, 3, 0, 0]} />
                <Bar dataKey="p50_render_s" name="Median (P50)" fill={TEAL} radius={[3, 3, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}

      {/* Row 6 — Top 10 Products + Category Revenue */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Top 10 Products</h2>
          {top_products.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border-light text-left">
                  <th className="py-2 pr-3 text-content-secondary font-medium">PIM-ID</th>
                  <th className="py-2 pr-3 text-content-secondary font-medium">Product</th>
                  <th className="py-2 pr-3 text-content-secondary font-medium">Category</th>
                  <th className="py-2 text-content-secondary font-medium text-right">Orders</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border-light">
                {top_products.map((p) => (
                  <tr key={p.pim_id}>
                    <td className="py-1.5 pr-3 font-mono text-xs text-content-muted">{p.pim_id}</td>
                    <td className="py-1.5 pr-3 text-content truncate max-w-[160px]">{p.product_name || '—'}</td>
                    <td className="py-1.5 pr-3 text-content-muted">{p.category}</td>
                    <td className="py-1.5 font-medium text-content text-right">{p.order_count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        <div className="card p-4">
          <h2 className="text-sm font-semibold text-content-secondary mb-3">Revenue by Category (€)</h2>
          {category_revenue.length === 0 ? (
            <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
          ) : (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={category_revenue} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
                <XAxis dataKey="category" tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <YAxis tick={{ fill: 'var(--color-text-muted)', fontSize: 10 }} />
                <Tooltip contentStyle={CHART_TOOLTIP_STYLE} formatter={(v: number | undefined) => v != null ? [`€ ${v.toFixed(2)}`, 'Revenue'] : ['—', 'Revenue']} />
                <Bar dataKey="revenue" radius={[3, 3, 0, 0]}>
                  {category_revenue.map((_, i) => (
                    <Cell key={i} fill={CATEGORY_COLORS[i % CATEGORY_COLORS.length]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* Row 7 — Orders by User */}
      <div className="card p-4">
        <h2 className="text-sm font-semibold text-content-secondary mb-3">Orders by User</h2>
        {orders_by_user.length === 0 ? (
          <p className="text-xs text-content-muted py-8 text-center">No data yet</p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border-light text-left">
                <th className="py-2 pr-3 text-content-secondary font-medium">Name</th>
                <th className="py-2 pr-3 text-content-secondary font-medium">Email</th>
                <th className="py-2 pr-3 text-content-secondary font-medium">Role</th>
                <th className="py-2 pr-3 text-content-secondary font-medium text-right">Orders</th>
                <th className="py-2 text-content-secondary font-medium text-right">Revenue (€)</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border-light">
              {orders_by_user.map((u) => (
                <tr key={u.email}>
                  <td className="py-1.5 pr-3 text-content">{u.full_name}</td>
                  <td className="py-1.5 pr-3 text-content-muted text-xs">{u.email}</td>
                  <td className="py-1.5 pr-3">
                    <span className="text-xs px-2 py-0.5 rounded-full bg-surface-muted text-content-secondary">
                      {u.role === 'project_manager' ? 'PM' : u.role}
                    </span>
                  </td>
                  <td className="py-1.5 pr-3 font-medium text-content text-right">{u.order_count}</td>
                  <td className="py-1.5 font-medium text-content text-right">€ {u.revenue.toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  )
}

function SummaryCard({ label, value }: { label: string; value: number | string }) {
  return (
    <div className="card p-5">
      <p className="text-2xl font-bold text-content">{value}</p>
      <p className="text-sm text-content-muted mt-1">{label}</p>
    </div>
  )
}

function MetricRow({ label, value }: { label: string; value: string }) {
  return (
    <tr>
      <td className="py-1.5 pr-3 text-content-secondary">{label}</td>
      <td className="py-1.5 font-medium text-content text-right">{value}</td>
    </tr>
  )
}
