'use client'

import { useEffect, useState, useCallback } from 'react'
import {
  TrendingUp,
  TrendingDown,
  DollarSign,
  ShoppingCart,
  Users,
  Clock,
  BarChart3,
  Package,
  AlertTriangle,
  Crown,
  UserPlus,
  RefreshCcw,
  Loader2,
  ArrowUpRight,
  ArrowDownRight,
  Utensils,
  Timer,
} from 'lucide-react'
import toast from 'react-hot-toast'
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
  AreaChart,
  Area,
} from 'recharts'
import { formatCurrency } from '@/lib/utils'
import { useAuthStore } from '@/store/auth-store'

// ============================================================
// Constants
// ============================================================

const COLORS = ['#f97316', '#3b82f6', '#10b981', '#8b5cf6', '#ef4444', '#f59e0b']

const ORDER_TYPE_LABELS: Record<string, string> = {
  dine_in: 'Dine In',
  takeaway: 'Takeaway',
  delivery: 'Delivery',
}

const DAY_LABELS = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab']

const MONTH_LABELS = [
  'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun',
  'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des',
]

const ATTENDANCE_COLORS: Record<string, string> = {
  present: '#10b981',
  late: '#f59e0b',
  absent: '#ef4444',
  excused: '#3b82f6',
}

const ATTENDANCE_LABELS: Record<string, string> = {
  present: 'Hadir',
  late: 'Terlambat',
  absent: 'Tidak Hadir',
  excused: 'Izin/Cuti',
}

const TAB_ITEMS = [
  { key: 'sales', label: 'Penjualan', icon: DollarSign },
  { key: 'products', label: 'Produk', icon: Package },
  { key: 'customers', label: 'Pelanggan', icon: Users },
  { key: 'operations', label: 'Operasional', icon: Clock },
] as const

type TabKey = (typeof TAB_ITEMS)[number]['key']

// ============================================================
// Types
// ============================================================

interface Store {
  id: string
  name: string
}

interface SalesData {
  revenueTrend: { date: string; revenue: number; orders: number }[]
  hourlyHeatmap: { hour: number; day: number; count: number }[]
  orderTypeBreakdown: { type: string; count: number; revenue: number }[]
  growth: {
    revenue: { current: number; previous: number; percentage: number }
    orders: { current: number; previous: number; percentage: number }
    avgOrderValue: { current: number; previous: number; percentage: number }
  }
}

interface ProductsData {
  menuPerformance: {
    id: string
    name: string
    category: string
    quantity: number
    revenue: number
    avgPrice: number
  }[]
  categoryBreakdown: { category: string; quantity: number; revenue: number }[]
  slowMoving: {
    id: string
    name: string
    category: string
    quantity: number
    lastOrdered: string
  }[]
  topCombos: { item1: string; item2: string; count: number }[]
}

interface CustomersData {
  acquisitionTrend: { month: string; newCustomers: number }[]
  topCustomers: {
    id: string
    name: string
    totalOrders: number
    totalSpent: number
    lastOrder: string
  }[]
  repeatRate: { total: number; repeat: number; percentage: number }
  segmentation: { new: number; returning: number; vip: number }
}

interface OperationsData {
  avgCompletionTime: { minutes: number; trend: number }
  peakHours: { hour: number; orders: number }[]
  tableUtilization: {
    tableId: string
    tableName: string
    reservations: number
    percentage: number
  }[]
  attendanceSummary: {
    present: number
    late: number
    absent: number
    excused: number
  }
  expenseVsRevenue: { month: string; expense: number; revenue: number }[]
}

// ============================================================
// Helper functions
// ============================================================

function formatCompactNumber(value: number): string {
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}jt`
  if (value >= 1_000) return `${(value / 1_000).toFixed(0)}k`
  return String(value)
}

function formatMonthLabel(monthStr: string): string {
  const parts = monthStr.split('-')
  if (parts.length < 2) return monthStr
  const monthIdx = parseInt(parts[1], 10) - 1
  return MONTH_LABELS[monthIdx] ?? monthStr
}

function formatDateLabel(dateStr: string): string {
  const parts = dateStr.split('-')
  return parts[parts.length - 1]?.replace(/^0/, '') ?? dateStr
}

// ============================================================
// Heatmap helper: build 7x24 grid from sparse data
// ============================================================

function buildHeatmapGrid(
  data: { hour: number; day: number; count: number }[]
): number[][] {
  const grid: number[][] = Array.from({ length: 7 }, () => Array(24).fill(0))
  for (const item of data) {
    if (item.day >= 0 && item.day < 7 && item.hour >= 0 && item.hour < 24) {
      grid[item.day][item.hour] = item.count
    }
  }
  return grid
}

function getHeatmapMaxCount(grid: number[][]): number {
  let max = 0
  for (const row of grid) {
    for (const val of row) {
      if (val > max) max = val
    }
  }
  return max || 1
}

// ============================================================
// Main Component
// ============================================================

export default function AnalyticsPage() {
  const { user } = useAuthStore()

  // Filters
  const [stores, setStores] = useState<Store[]>([])
  const [storeId, setStoreId] = useState('')
  const [period, setPeriod] = useState('30d')
  const [activeTab, setActiveTab] = useState<TabKey>('sales')

  // Tab data (cached independently)
  const [salesData, setSalesData] = useState<SalesData | null>(null)
  const [productsData, setProductsData] = useState<ProductsData | null>(null)
  const [customersData, setCustomersData] = useState<CustomersData | null>(null)
  const [operationsData, setOperationsData] = useState<OperationsData | null>(null)

  // Loading states per tab
  const [salesLoading, setSalesLoading] = useState(false)
  const [productsLoading, setProductsLoading] = useState(false)
  const [customersLoading, setCustomersLoading] = useState(false)
  const [operationsLoading, setOperationsLoading] = useState(false)

  // Track which tab+filter combos have been fetched
  const [salesKey, setSalesKey] = useState('')
  const [productsKey, setProductsKey] = useState('')
  const [customersKey, setCustomersKey] = useState('')
  const [operationsKey, setOperationsKey] = useState('')

  const userHasStore = !!user?.storeId

  // --------------------------------------------------------
  // Fetch stores
  // --------------------------------------------------------
  useEffect(() => {
    if (userHasStore) return
    fetch('/api/stores')
      .then((r) => r.json())
      .then((d) => setStores(d.stores || []))
      .catch(() => {})
  }, [userHasStore])

  // Determine effective storeId
  const effectiveStoreId = userHasStore ? (user?.storeId ?? '') : storeId

  // --------------------------------------------------------
  // Fetch functions
  // --------------------------------------------------------
  const fetchSales = useCallback(async () => {
    const key = `sales-${effectiveStoreId}-${period}`
    if (key === salesKey) return
    setSalesLoading(true)
    try {
      const params = new URLSearchParams({ period })
      if (effectiveStoreId) params.set('storeId', effectiveStoreId)
      const res = await fetch(`/api/analytics/sales?${params}`)
      if (!res.ok) throw new Error('Gagal memuat data penjualan')
      const d = await res.json()
      setSalesData(d)
      setSalesKey(key)
    } catch (err: any) {
      toast.error(err.message || 'Gagal memuat data penjualan')
    } finally {
      setSalesLoading(false)
    }
  }, [effectiveStoreId, period, salesKey])

  const fetchProducts = useCallback(async () => {
    const key = `products-${effectiveStoreId}-${period}`
    if (key === productsKey) return
    setProductsLoading(true)
    try {
      const params = new URLSearchParams({ period })
      if (effectiveStoreId) params.set('storeId', effectiveStoreId)
      const res = await fetch(`/api/analytics/products?${params}`)
      if (!res.ok) throw new Error('Gagal memuat data produk')
      const d = await res.json()
      setProductsData(d)
      setProductsKey(key)
    } catch (err: any) {
      toast.error(err.message || 'Gagal memuat data produk')
    } finally {
      setProductsLoading(false)
    }
  }, [effectiveStoreId, period, productsKey])

  const fetchCustomers = useCallback(async () => {
    const key = `customers-${period}`
    if (key === customersKey) return
    setCustomersLoading(true)
    try {
      const params = new URLSearchParams({ period })
      const res = await fetch(`/api/analytics/customers?${params}`)
      if (!res.ok) throw new Error('Gagal memuat data pelanggan')
      const d = await res.json()
      setCustomersData(d)
      setCustomersKey(key)
    } catch (err: any) {
      toast.error(err.message || 'Gagal memuat data pelanggan')
    } finally {
      setCustomersLoading(false)
    }
  }, [period, customersKey])

  const fetchOperations = useCallback(async () => {
    const key = `operations-${effectiveStoreId}-${period}`
    if (key === operationsKey) return
    setOperationsLoading(true)
    try {
      const params = new URLSearchParams({ period })
      if (effectiveStoreId) params.set('storeId', effectiveStoreId)
      const res = await fetch(`/api/analytics/operations?${params}`)
      if (!res.ok) throw new Error('Gagal memuat data operasional')
      const d = await res.json()
      setOperationsData(d)
      setOperationsKey(key)
    } catch (err: any) {
      toast.error(err.message || 'Gagal memuat data operasional')
    } finally {
      setOperationsLoading(false)
    }
  }, [effectiveStoreId, period, operationsKey])

  // --------------------------------------------------------
  // Lazy fetch on tab switch or filter change
  // --------------------------------------------------------
  useEffect(() => {
    if (activeTab === 'sales') fetchSales()
    else if (activeTab === 'products') fetchProducts()
    else if (activeTab === 'customers') fetchCustomers()
    else if (activeTab === 'operations') fetchOperations()
  }, [activeTab, fetchSales, fetchProducts, fetchCustomers, fetchOperations])

  // Invalidate cache when filters change
  useEffect(() => {
    setSalesKey('')
    setProductsKey('')
    setCustomersKey('')
    setOperationsKey('')
  }, [effectiveStoreId, period])

  // --------------------------------------------------------
  // Render helpers
  // --------------------------------------------------------
  const renderLoading = () => (
    <div className="flex items-center justify-center h-64">
      <Loader2 className="w-8 h-8 animate-spin text-primary-600" />
    </div>
  )

  const renderEmpty = (message = 'Belum ada data') => (
    <p className="text-center text-gray-500 dark:text-gray-400 py-12">{message}</p>
  )

  // ============================================================
  // TAB 1: Penjualan (Sales)
  // ============================================================
  const renderSalesTab = () => {
    if (salesLoading) return renderLoading()
    if (!salesData) return renderEmpty()

    const { growth, revenueTrend, orderTypeBreakdown, hourlyHeatmap } = salesData

    const growthCards = [
      {
        label: 'Pendapatan',
        value: formatCurrency(growth?.revenue?.current ?? 0),
        pct: growth?.revenue?.percentage ?? 0,
        icon: DollarSign,
        bg: 'bg-green-100 dark:bg-green-900/30',
        iconColor: 'text-green-600',
      },
      {
        label: 'Total Order',
        value: String(growth?.orders?.current ?? 0),
        pct: growth?.orders?.percentage ?? 0,
        icon: ShoppingCart,
        bg: 'bg-blue-100 dark:bg-blue-900/30',
        iconColor: 'text-blue-600',
      },
      {
        label: 'Rata-rata Order',
        value: formatCurrency(growth?.avgOrderValue?.current ?? 0),
        pct: growth?.avgOrderValue?.percentage ?? 0,
        icon: TrendingUp,
        bg: 'bg-purple-100 dark:bg-purple-900/30',
        iconColor: 'text-purple-600',
      },
    ]

    const heatmapGrid = buildHeatmapGrid(hourlyHeatmap || [])
    const heatmapMax = getHeatmapMaxCount(heatmapGrid)

    const orderTypeData = (orderTypeBreakdown || []).map((item) => ({
      ...item,
      label: ORDER_TYPE_LABELS[item.type] ?? item.type,
    }))

    return (
      <div className="space-y-6">
        {/* Growth Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {growthCards.map((card) => (
            <div key={card.label} className="card">
              <div className="flex items-center gap-3">
                <div className={`w-10 h-10 ${card.bg} rounded-lg flex items-center justify-center`}>
                  <card.icon className={`w-5 h-5 ${card.iconColor}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-gray-600 dark:text-gray-300">{card.label}</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-white truncate">
                    {card.value}
                  </p>
                </div>
                <div
                  className={`flex items-center gap-1 text-sm font-medium ${
                    card.pct >= 0 ? 'text-green-600' : 'text-red-600'
                  }`}
                >
                  {card.pct >= 0 ? (
                    <ArrowUpRight className="w-4 h-4" />
                  ) : (
                    <ArrowDownRight className="w-4 h-4" />
                  )}
                  {Math.abs(card.pct).toFixed(1)}%
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Revenue Trend */}
        <div className="card">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Tren Pendapatan
          </h2>
          {revenueTrend && revenueTrend.length > 0 ? (
            <ResponsiveContainer width="100%" height={320}>
              <AreaChart data={revenueTrend}>
                <defs>
                  <linearGradient id="revenueGradient" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#f97316" stopOpacity={0.3} />
                    <stop offset="95%" stopColor="#f97316" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" className="dark:opacity-20" />
                <XAxis
                  dataKey="date"
                  tick={{ fontSize: 12 }}
                  tickFormatter={formatDateLabel}
                  stroke="#888"
                />
                <YAxis
                  tick={{ fontSize: 12 }}
                  tickFormatter={(v) => formatCompactNumber(v)}
                  stroke="#888"
                />
                <Tooltip
                  formatter={(value: number, name: string) => {
                    if (name === 'revenue') return [formatCurrency(value), 'Pendapatan']
                    return [value, 'Order']
                  }}
                  labelFormatter={(label) => `Tanggal: ${label}`}
                  contentStyle={{
                    backgroundColor: 'rgba(255,255,255,0.95)',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                  }}
                />
                <Area
                  type="monotone"
                  dataKey="revenue"
                  stroke="#f97316"
                  strokeWidth={2}
                  fill="url(#revenueGradient)"
                />
                <Line
                  type="monotone"
                  dataKey="orders"
                  stroke="#3b82f6"
                  strokeWidth={2}
                  dot={false}
                  yAxisId={0}
                />
              </AreaChart>
            </ResponsiveContainer>
          ) : (
            renderEmpty()
          )}
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* Order Type Breakdown */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Breakdown Tipe Order
            </h2>
            {orderTypeData.length > 0 ? (
              <ResponsiveContainer width="100%" height={280}>
                <PieChart>
                  <Pie
                    data={orderTypeData}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={100}
                    dataKey="count"
                    nameKey="label"
                    label={({ label, percent }) =>
                      `${label} ${(percent * 100).toFixed(0)}%`
                    }
                  >
                    {orderTypeData.map((_, idx) => (
                      <Cell key={idx} fill={COLORS[idx % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value: number, name: string, props: any) => {
                      return [
                        `${value} order (${formatCurrency(props.payload.revenue)})`,
                        props.payload.label,
                      ]
                    }}
                  />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              renderEmpty()
            )}
          </div>

          {/* Hourly Heatmap */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Heatmap Order per Jam
            </h2>
            {hourlyHeatmap && hourlyHeatmap.length > 0 ? (
              <div className="overflow-x-auto">
                <div className="min-w-[600px]">
                  {/* Hour headers */}
                  <div className="flex items-center gap-[2px] mb-[2px]">
                    <div className="w-10 flex-shrink-0" />
                    {Array.from({ length: 24 }, (_, h) => (
                      <div
                        key={h}
                        className="flex-1 text-center text-[10px] text-gray-500 dark:text-gray-400"
                      >
                        {h}
                      </div>
                    ))}
                  </div>
                  {/* Rows */}
                  {heatmapGrid.map((row, dayIdx) => (
                    <div key={dayIdx} className="flex items-center gap-[2px] mb-[2px]">
                      <div className="w-10 flex-shrink-0 text-xs text-gray-600 dark:text-gray-300 font-medium">
                        {DAY_LABELS[dayIdx]}
                      </div>
                      {row.map((count, hourIdx) => {
                        const intensity = count / heatmapMax
                        return (
                          <div
                            key={hourIdx}
                            className="flex-1 aspect-square rounded-sm cursor-default"
                            style={{
                              backgroundColor:
                                count === 0
                                  ? 'rgba(156, 163, 175, 0.1)'
                                  : `rgba(249, 115, 22, ${0.15 + intensity * 0.85})`,
                            }}
                            title={`${DAY_LABELS[dayIdx]} ${String(hourIdx).padStart(2, '0')}:00 - ${count} order`}
                          />
                        )
                      })}
                    </div>
                  ))}
                  {/* Legend */}
                  <div className="flex items-center justify-end gap-2 mt-3">
                    <span className="text-xs text-gray-500 dark:text-gray-400">Sedikit</span>
                    {[0.15, 0.35, 0.55, 0.75, 1].map((opacity, i) => (
                      <div
                        key={i}
                        className="w-4 h-4 rounded-sm"
                        style={{ backgroundColor: `rgba(249, 115, 22, ${opacity})` }}
                      />
                    ))}
                    <span className="text-xs text-gray-500 dark:text-gray-400">Banyak</span>
                  </div>
                </div>
              </div>
            ) : (
              renderEmpty()
            )}
          </div>
        </div>
      </div>
    )
  }

  // ============================================================
  // TAB 2: Produk (Products)
  // ============================================================
  const renderProductsTab = () => {
    if (productsLoading) return renderLoading()
    if (!productsData) return renderEmpty()

    const { menuPerformance, categoryBreakdown, slowMoving, topCombos } = productsData

    return (
      <div className="space-y-6">
        {/* Menu Performance Table */}
        <div className="card">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Performa Menu
          </h2>
          {menuPerformance && menuPerformance.length > 0 ? (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-200 dark:border-gray-700">
                    <th className="text-left py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                      #
                    </th>
                    <th className="text-left py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                      Item
                    </th>
                    <th className="text-left py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                      Kategori
                    </th>
                    <th className="text-right py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                      Terjual
                    </th>
                    <th className="text-right py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                      Pendapatan
                    </th>
                    <th className="text-right py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                      Rata-rata Harga
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {menuPerformance.map((item, idx) => (
                    <tr
                      key={item.id}
                      className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50"
                    >
                      <td className="py-3 px-2">
                        <span className="w-6 h-6 bg-primary-100 dark:bg-primary-900/30 rounded-full inline-flex items-center justify-center text-xs font-bold text-primary-700 dark:text-primary-300">
                          {idx + 1}
                        </span>
                      </td>
                      <td className="py-3 px-2 font-medium text-gray-900 dark:text-white">
                        {item.name}
                      </td>
                      <td className="py-3 px-2">
                        <span className="badge bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300">
                          {item.category}
                        </span>
                      </td>
                      <td className="py-3 px-2 text-right text-gray-700 dark:text-gray-300">
                        {item.quantity}
                      </td>
                      <td className="py-3 px-2 text-right text-gray-900 dark:text-white font-medium">
                        {formatCurrency(item.revenue)}
                      </td>
                      <td className="py-3 px-2 text-right text-gray-700 dark:text-gray-300">
                        {formatCurrency(item.avgPrice)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            renderEmpty()
          )}
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* Category Breakdown */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Breakdown Kategori
            </h2>
            {categoryBreakdown && categoryBreakdown.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={categoryBreakdown} layout="vertical">
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" className="dark:opacity-20" />
                  <XAxis
                    type="number"
                    tick={{ fontSize: 12 }}
                    tickFormatter={(v) => formatCompactNumber(v)}
                    stroke="#888"
                  />
                  <YAxis
                    type="category"
                    dataKey="category"
                    tick={{ fontSize: 12 }}
                    width={100}
                    stroke="#888"
                  />
                  <Tooltip
                    formatter={(value: number, name: string) => {
                      if (name === 'revenue') return [formatCurrency(value), 'Pendapatan']
                      return [value, 'Terjual']
                    }}
                  />
                  <Bar dataKey="revenue" fill="#f97316" radius={[0, 4, 4, 0]} name="revenue" />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              renderEmpty()
            )}
          </div>

          {/* Slow Moving Items */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-yellow-500" />
              Item Lambat Terjual
            </h2>
            {slowMoving && slowMoving.length > 0 ? (
              <div className="space-y-3">
                {slowMoving.map((item) => (
                  <div
                    key={item.id}
                    className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-900/10 border border-yellow-200 dark:border-yellow-800/30"
                  >
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium text-gray-900 dark:text-white">
                          {item.name}
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          {item.category} &middot; {item.quantity} terjual
                        </p>
                      </div>
                      <div className="text-right">
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          Terakhir dipesan
                        </p>
                        <p className="text-sm font-medium text-yellow-700 dark:text-yellow-400">
                          {new Date(item.lastOrdered).toLocaleDateString('id-ID', {
                            day: 'numeric',
                            month: 'short',
                            year: 'numeric',
                          })}
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              renderEmpty('Tidak ada item lambat terjual')
            )}
          </div>
        </div>

        {/* Top Combos */}
        <div className="card">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
            <Utensils className="w-5 h-5 text-primary-500" />
            Kombinasi Favorit
          </h2>
          {topCombos && topCombos.length > 0 ? (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
              {topCombos.map((combo, idx) => (
                <div
                  key={idx}
                  className="flex items-center gap-3 p-3 rounded-lg bg-gray-50 dark:bg-gray-800/50 border border-gray-100 dark:border-gray-700"
                >
                  <span className="w-8 h-8 bg-primary-100 dark:bg-primary-900/30 rounded-full flex items-center justify-center text-sm font-bold text-primary-700 dark:text-primary-300">
                    {idx + 1}
                  </span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                      {combo.item1}
                    </p>
                    <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
                      + {combo.item2}
                    </p>
                  </div>
                  <span className="text-sm font-semibold text-primary-600 dark:text-primary-400">
                    {combo.count}x
                  </span>
                </div>
              ))}
            </div>
          ) : (
            renderEmpty('Belum ada data kombinasi')
          )}
        </div>
      </div>
    )
  }

  // ============================================================
  // TAB 3: Pelanggan (Customers)
  // ============================================================
  const renderCustomersTab = () => {
    if (customersLoading) return renderLoading()
    if (!customersData) return renderEmpty()

    const { segmentation, repeatRate, topCustomers, acquisitionTrend } = customersData

    const segCards = [
      {
        label: 'Pelanggan Baru',
        value: segmentation?.new ?? 0,
        icon: UserPlus,
        bg: 'bg-blue-100 dark:bg-blue-900/30',
        iconColor: 'text-blue-600',
        valueColor: 'text-blue-700 dark:text-blue-300',
      },
      {
        label: 'Pelanggan Kembali',
        value: segmentation?.returning ?? 0,
        icon: RefreshCcw,
        bg: 'bg-green-100 dark:bg-green-900/30',
        iconColor: 'text-green-600',
        valueColor: 'text-green-700 dark:text-green-300',
      },
      {
        label: 'Pelanggan VIP',
        value: segmentation?.vip ?? 0,
        icon: Crown,
        bg: 'bg-purple-100 dark:bg-purple-900/30',
        iconColor: 'text-purple-600',
        valueColor: 'text-purple-700 dark:text-purple-300',
      },
    ]

    const acquisitionData = (acquisitionTrend || []).map((item) => ({
      ...item,
      monthLabel: formatMonthLabel(item.month),
    }))

    return (
      <div className="space-y-6">
        {/* Segmentation Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {segCards.map((card) => (
            <div key={card.label} className="card">
              <div className="flex items-center gap-3">
                <div className={`w-12 h-12 ${card.bg} rounded-xl flex items-center justify-center`}>
                  <card.icon className={`w-6 h-6 ${card.iconColor}`} />
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-300">{card.label}</p>
                  <p className={`text-2xl font-bold ${card.valueColor}`}>{card.value}</p>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Repeat Rate */}
        <div className="card text-center py-8">
          <p className="text-sm text-gray-600 dark:text-gray-300 mb-2">Tingkat Pelanggan Kembali</p>
          <p className="text-5xl font-bold text-primary-600 dark:text-primary-400">
            {repeatRate?.percentage ?? 0}%
          </p>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-2">
            {repeatRate?.repeat ?? 0} dari {repeatRate?.total ?? 0} pelanggan kembali
          </p>
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* Top Customer Leaderboard */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Pelanggan Teratas
            </h2>
            {topCustomers && topCustomers.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-200 dark:border-gray-700">
                      <th className="text-left py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                        #
                      </th>
                      <th className="text-left py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                        Nama
                      </th>
                      <th className="text-right py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                        Total Order
                      </th>
                      <th className="text-right py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                        Total Belanja
                      </th>
                      <th className="text-right py-3 px-2 font-medium text-gray-600 dark:text-gray-300">
                        Terakhir Order
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {topCustomers.map((customer, idx) => (
                      <tr
                        key={customer.id}
                        className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50"
                      >
                        <td className="py-3 px-2">
                          <span
                            className={`w-6 h-6 rounded-full inline-flex items-center justify-center text-xs font-bold ${
                              idx < 3
                                ? 'bg-primary-100 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300'
                                : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
                            }`}
                          >
                            {idx + 1}
                          </span>
                        </td>
                        <td className="py-3 px-2 font-medium text-gray-900 dark:text-white">
                          {customer.name}
                        </td>
                        <td className="py-3 px-2 text-right text-gray-700 dark:text-gray-300">
                          {customer.totalOrders}
                        </td>
                        <td className="py-3 px-2 text-right text-gray-900 dark:text-white font-medium">
                          {formatCurrency(customer.totalSpent)}
                        </td>
                        <td className="py-3 px-2 text-right text-gray-500 dark:text-gray-400">
                          {new Date(customer.lastOrder).toLocaleDateString('id-ID', {
                            day: 'numeric',
                            month: 'short',
                          })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              renderEmpty()
            )}
          </div>

          {/* Acquisition Trend */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Tren Akuisisi Pelanggan
            </h2>
            {acquisitionData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={acquisitionData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" className="dark:opacity-20" />
                  <XAxis
                    dataKey="monthLabel"
                    tick={{ fontSize: 12 }}
                    stroke="#888"
                  />
                  <YAxis tick={{ fontSize: 12 }} stroke="#888" />
                  <Tooltip
                    formatter={(value: number) => [value, 'Pelanggan Baru']}
                    labelFormatter={(label) => `Bulan: ${label}`}
                  />
                  <Bar
                    dataKey="newCustomers"
                    fill="#3b82f6"
                    radius={[4, 4, 0, 0]}
                    name="Pelanggan Baru"
                  />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              renderEmpty()
            )}
          </div>
        </div>
      </div>
    )
  }

  // ============================================================
  // TAB 4: Operasional (Operations)
  // ============================================================
  const renderOperationsTab = () => {
    if (operationsLoading) return renderLoading()
    if (!operationsData) return renderEmpty()

    const {
      avgCompletionTime,
      peakHours,
      tableUtilization,
      attendanceSummary,
      expenseVsRevenue,
    } = operationsData

    const peakHourData = (peakHours || []).map((item) => ({
      ...item,
      hourLabel: `${String(item.hour).padStart(2, '0')}:00`,
    }))

    const peakMax = peakHourData.reduce(
      (max, item) => (item.orders > max ? item.orders : max),
      0
    )

    const attendanceData = attendanceSummary
      ? [
          { name: 'Hadir', value: attendanceSummary.present, color: ATTENDANCE_COLORS.present },
          { name: 'Terlambat', value: attendanceSummary.late, color: ATTENDANCE_COLORS.late },
          { name: 'Tidak Hadir', value: attendanceSummary.absent, color: ATTENDANCE_COLORS.absent },
          { name: 'Izin/Cuti', value: attendanceSummary.excused, color: ATTENDANCE_COLORS.excused },
        ]
      : []

    const attendanceTotal = attendanceData.reduce((sum, d) => sum + d.value, 0)

    const expenseRevenueData = (expenseVsRevenue || []).map((item) => ({
      ...item,
      monthLabel: formatMonthLabel(item.month),
    }))

    const maxUtilization = tableUtilization
      ? Math.max(...tableUtilization.map((t) => t.percentage), 1)
      : 1

    return (
      <div className="space-y-6">
        {/* Summary Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {/* Average Completion Time */}
          <div className="card">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-blue-100 dark:bg-blue-900/30 rounded-xl flex items-center justify-center">
                <Timer className="w-6 h-6 text-blue-600" />
              </div>
              <div className="flex-1">
                <p className="text-sm text-gray-600 dark:text-gray-300">
                  Rata-rata Waktu Selesai
                </p>
                <div className="flex items-center gap-2">
                  <p className="text-2xl font-bold text-gray-900 dark:text-white">
                    {avgCompletionTime?.minutes ?? 0} menit
                  </p>
                  {avgCompletionTime && avgCompletionTime.trend !== 0 && (
                    <span
                      className={`flex items-center gap-0.5 text-sm font-medium ${
                        avgCompletionTime.trend < 0 ? 'text-green-600' : 'text-red-600'
                      }`}
                    >
                      {avgCompletionTime.trend < 0 ? (
                        <TrendingDown className="w-4 h-4" />
                      ) : (
                        <TrendingUp className="w-4 h-4" />
                      )}
                      {Math.abs(avgCompletionTime.trend)} menit
                    </span>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Attendance Summary Donut */}
          <div className="card">
            <p className="text-sm text-gray-600 dark:text-gray-300 mb-3">Kehadiran Staf</p>
            {attendanceTotal > 0 ? (
              <div className="flex items-center gap-4">
                <div className="w-28 h-28 flex-shrink-0">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={attendanceData}
                        cx="50%"
                        cy="50%"
                        innerRadius={28}
                        outerRadius={48}
                        dataKey="value"
                        strokeWidth={0}
                      >
                        {attendanceData.map((entry, idx) => (
                          <Cell key={idx} fill={entry.color} />
                        ))}
                      </Pie>
                    </PieChart>
                  </ResponsiveContainer>
                </div>
                <div className="flex-1 space-y-1.5">
                  {attendanceData.map((entry) => (
                    <div key={entry.name} className="flex items-center justify-between text-sm">
                      <div className="flex items-center gap-2">
                        <div
                          className="w-3 h-3 rounded-full flex-shrink-0"
                          style={{ backgroundColor: entry.color }}
                        />
                        <span className="text-gray-600 dark:text-gray-300">{entry.name}</span>
                      </div>
                      <span className="font-medium text-gray-900 dark:text-white">
                        {entry.value}%
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              renderEmpty('Belum ada data kehadiran')
            )}
          </div>
        </div>

        {/* Peak Hours */}
        <div className="card">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            Jam Sibuk
          </h2>
          {peakHourData.length > 0 ? (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={peakHourData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" className="dark:opacity-20" />
                <XAxis
                  dataKey="hourLabel"
                  tick={{ fontSize: 11 }}
                  interval={1}
                  stroke="#888"
                />
                <YAxis tick={{ fontSize: 12 }} stroke="#888" />
                <Tooltip
                  formatter={(value: number) => [value, 'Order']}
                  labelFormatter={(label) => `Jam ${label}`}
                />
                <Bar
                  dataKey="orders"
                  radius={[4, 4, 0, 0]}
                  name="Order"
                >
                  {peakHourData.map((entry, idx) => (
                    <Cell
                      key={idx}
                      fill={entry.orders === peakMax && peakMax > 0 ? '#f97316' : '#fdba74'}
                    />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          ) : (
            renderEmpty()
          )}
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* Table Utilization */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Utilisasi Meja
            </h2>
            {tableUtilization && tableUtilization.length > 0 ? (
              <div className="space-y-3">
                {tableUtilization.map((table) => (
                  <div key={table.tableId}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                        {table.tableName}
                      </span>
                      <span className="text-xs text-gray-500 dark:text-gray-400">
                        {table.reservations} reservasi &middot; {table.percentage}%
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5">
                      <div
                        className="h-2.5 rounded-full transition-all duration-300"
                        style={{
                          width: `${Math.min(table.percentage, 100)}%`,
                          backgroundColor:
                            table.percentage >= 80
                              ? '#ef4444'
                              : table.percentage >= 50
                              ? '#f97316'
                              : '#10b981',
                        }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              renderEmpty('Belum ada data utilisasi meja')
            )}
          </div>

          {/* Expense vs Revenue */}
          <div className="card">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Pengeluaran vs Pendapatan
            </h2>
            {expenseRevenueData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <LineChart data={expenseRevenueData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" className="dark:opacity-20" />
                  <XAxis
                    dataKey="monthLabel"
                    tick={{ fontSize: 12 }}
                    stroke="#888"
                  />
                  <YAxis
                    tick={{ fontSize: 12 }}
                    tickFormatter={(v) => formatCompactNumber(v)}
                    stroke="#888"
                  />
                  <Tooltip
                    formatter={(value: number, name: string) => [
                      formatCurrency(value),
                      name === 'revenue' ? 'Pendapatan' : 'Pengeluaran',
                    ]}
                    labelFormatter={(label) => `Bulan: ${label}`}
                  />
                  <Legend
                    formatter={(value: string) =>
                      value === 'revenue' ? 'Pendapatan' : 'Pengeluaran'
                    }
                  />
                  <Line
                    type="monotone"
                    dataKey="revenue"
                    stroke="#10b981"
                    strokeWidth={2}
                    dot={{ r: 4, fill: '#10b981' }}
                    name="revenue"
                  />
                  <Line
                    type="monotone"
                    dataKey="expense"
                    stroke="#ef4444"
                    strokeWidth={2}
                    dot={{ r: 4, fill: '#ef4444' }}
                    name="expense"
                  />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              renderEmpty()
            )}
          </div>
        </div>
      </div>
    )
  }

  // ============================================================
  // Tab content router
  // ============================================================
  const renderTabContent = () => {
    switch (activeTab) {
      case 'sales':
        return renderSalesTab()
      case 'products':
        return renderProductsTab()
      case 'customers':
        return renderCustomersTab()
      case 'operations':
        return renderOperationsTab()
      default:
        return null
    }
  }

  // ============================================================
  // Main render
  // ============================================================
  return (
    <div>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Analitik Lanjutan</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-1">
            Insight mendalam untuk pengambilan keputusan bisnis.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {!userHasStore && (
            <select
              className="input-field w-auto text-sm"
              value={storeId}
              onChange={(e) => setStoreId(e.target.value)}
            >
              <option value="">Semua Cabang</option>
              {stores.map((s) => (
                <option key={s.id} value={s.id}>
                  {s.name}
                </option>
              ))}
            </select>
          )}
          <select
            className="input-field w-auto text-sm"
            value={period}
            onChange={(e) => setPeriod(e.target.value)}
          >
            <option value="7d">7 Hari</option>
            <option value="30d">30 Hari</option>
            <option value="90d">90 Hari</option>
          </select>
        </div>
      </div>

      {/* Tab Bar */}
      <div className="mb-6 -mx-1 overflow-x-auto">
        <div className="flex gap-1 px-1 min-w-max">
          {TAB_ITEMS.map((tab) => {
            const isActive = activeTab === tab.key
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
                  isActive
                    ? 'bg-primary-600 text-white shadow-sm'
                    : 'text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800'
                }`}
              >
                <tab.icon className="w-4 h-4" />
                {tab.label}
              </button>
            )
          })}
        </div>
      </div>

      {/* Tab Content */}
      {renderTabContent()}
    </div>
  )
}
