'use client'

import { Suspense, useEffect, useState, useCallback, useRef, useMemo } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import {
  ChefHat, Clock, CheckCircle2, ArrowLeft, RefreshCw, Volume2, VolumeX,
  AlertCircle, Package, Coffee, WifiOff, Printer, Ban, BellRing, Bell
} from 'lucide-react'
import { formatCurrency, ORDER_ITEM_STATUSES } from '@/lib/utils'
import toast from 'react-hot-toast'
import { useSSE } from '@/hooks/useSSE'
import { useBrowserNotification } from '@/hooks/useBrowserNotification'
import { printReceipt, orderToReceiptData, ThermalPrintOptions, extractReceiptTemplate } from '@/lib/print-receipt'
import { useThermalPrinter } from '@/hooks/useThermalPrinter'
import { useFeatureGuard } from '@/hooks/useFeatureGuard'
import FeatureBlockedPage from '@/components/FeatureBlockedPage'

export default function KitchenPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-gray-900">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
      </div>
    }>
      <KitchenPageInner />
    </Suspense>
  )
}

function KitchenPageInner() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { allowed: featureAllowed, loading: featureLoading } = useFeatureGuard('kitchen_display')
  const [orders, setOrders] = useState<any[]>([])
  const [stores, setStores] = useState<any[]>([])
  const [selectedStore, setSelectedStore] = useState('')
  const [loading, setLoading] = useState(true)
  const [user, setUser] = useState<any>(null)
  const [soundEnabled, setSoundEnabled] = useState(true)
  const [lastOrderCount, setLastOrderCount] = useState(0)
  const { permission: notifPermission, requestPermission, notify } = useBrowserNotification()
  const [stations, setStations] = useState<any[]>([])
  const [selectedStation, setSelectedStation] = useState(searchParams.get('station') || 'all')
  const printer = useThermalPrinter()
  const [printerSettings, setPrinterSettings] = useState({
    thermal_printer_enabled: 'false',
    thermal_paper_width: '80mm',
    thermal_auto_print_receipt: 'false',
    thermal_auto_print_kitchen: 'false',
    receipt_show_browser_popup: 'true',
  })

  useEffect(() => {
    fetch('/api/settings/printer')
      .then(r => r.json())
      .then(d => { if (d.settings) setPrinterSettings(d.settings) })
      .catch(() => {})
  }, [])

  const thermalOpts: ThermalPrintOptions | undefined =
    printer.isConnected && printerSettings.thermal_printer_enabled === 'true'
      ? { print: printer.print, paper: printerSettings.thermal_paper_width as '58mm' | '80mm' }
      : undefined

  const receiptTemplate = extractReceiptTemplate(printerSettings)

  // Refs for auto-print (SSE callback needs latest values)
  const thermalOptsRef = useRef(thermalOpts)
  const printerSettingsRef = useRef(printerSettings)
  const receiptTemplateRef = useRef(receiptTemplate)
  const userRef = useRef(user)
  const storesRef = useRef(stores)
  const selectedStoreRef = useRef(selectedStore)
  const stationsRef = useRef(stations)
  const selectedStationRef = useRef(selectedStation)
  useEffect(() => { thermalOptsRef.current = thermalOpts }, [thermalOpts])
  useEffect(() => { printerSettingsRef.current = printerSettings }, [printerSettings])
  useEffect(() => { receiptTemplateRef.current = receiptTemplate }, [receiptTemplate])
  useEffect(() => { userRef.current = user }, [user])
  useEffect(() => { storesRef.current = stores }, [stores])
  useEffect(() => { selectedStoreRef.current = selectedStore }, [selectedStore])
  useEffect(() => { stationsRef.current = stations }, [stations])
  useEffect(() => { selectedStationRef.current = selectedStation }, [selectedStation])

  const handleAutoKitchenPrint = useCallback(async (orderData: any) => {
    const settings = printerSettingsRef.current
    if (settings.thermal_auto_print_kitchen !== 'true') return

    // Fetch full order data for receipt (SSE data may be partial)
    try {
      const orderId = orderData?.orderId || orderData?.id
      if (!orderId) return
      const res = await fetch(`/api/orders/${orderId}`)
      if (!res.ok) return
      const data = await res.json()
      const order = data.order
      if (!order) return

      const store = storesRef.current.find((s: any) => s.id === selectedStoreRef.current)
      const restaurantName = userRef.current?.tenant?.name || store?.name || '-'
      const storeName = store?.name || ''

      // Filter items by selected station
      const stationId = selectedStationRef.current
      let printItems = order.items
      let stationName = ''
      if (stationId && stationId !== 'all') {
        printItems = order.items?.filter((item: any) => {
          const itemStationId = item.menuItem?.category?.kitchenStationId
          return itemStationId === stationId
        })
        stationName = stationsRef.current.find((s: any) => s.id === stationId)?.name || ''
      }
      if (!printItems || printItems.length === 0) return

      const filteredOrder = { ...order, items: printItems }
      const receiptData = orderToReceiptData(filteredOrder, restaurantName, storeName, { stationName })
      const opts = thermalOptsRef.current
      const template = receiptTemplateRef.current

      const showPopup = settings.receipt_show_browser_popup !== 'false'
      const result = await printReceipt(receiptData, 'kitchen', opts, template, showPopup)
      if (result.success) console.log('[KITCHEN] Auto print tiket dapur berhasil via', result.method)
      else console.error('[KITCHEN] Auto print gagal:', result.error)
    } catch (e) {
      console.error('[KITCHEN] Auto print error:', e)
    }
  }, [])

  const { status: sseStatus, showReconnected } = useSSE({
    storeId: selectedStore,
    onOrderCreated: (data: any) => {
      fetchOrders()
      handleAutoKitchenPrint(data)
      const info = data.tableNumber ? `Meja ${data.tableNumber}` : (data.orderType === 'takeaway' ? 'Takeaway' : '')
      notify('🔔 Pesanan Baru!', {
        body: `Order ${data.orderNumber || ''}${info ? ' - ' + info : ''}`,
        tag: `order-${data.orderId}`,
      })
    },
    onOrderUpdated: () => fetchOrders(),
    onOrderItemUpdated: () => fetchOrders(),
    onNotificationCreated: () => fetchOrders(),
    enabled: !!selectedStore,
  })

  const handlePrintKitchenTicket = useCallback((order: any) => {
    const store = stores.find((s: any) => s.id === selectedStore)
    const restaurantName = user?.tenant?.name || store?.name || '-'
    const storeName = store?.name || ''

    // Filter items by station for print
    let printItems = order.items
    let stationName = ''
    if (selectedStation && selectedStation !== 'all') {
      printItems = order.items?.filter((item: any) => {
        const itemStationId = item.menuItem?.category?.kitchenStationId
        return itemStationId === selectedStation
      })
      stationName = stations.find((s: any) => s.id === selectedStation)?.name || ''
    }
    if (!printItems || printItems.length === 0) return

    const filteredOrder = { ...order, items: printItems }
    const receiptData = orderToReceiptData(filteredOrder, restaurantName, storeName, { stationName })
    printReceipt(receiptData, 'kitchen', thermalOpts, receiptTemplate)
  }, [stores, selectedStore, user, thermalOpts, receiptTemplate, selectedStation, stations])

  const fetchOrders = useCallback(async () => {
    try {
      const params = new URLSearchParams()
      if (selectedStore) params.set('storeId', selectedStore)
      const res = await fetch(`/api/orders?${params}`)
      const data = await res.json()
      const kitchenOrders = (data.orders || []).filter(
        (o: any) => ['pending', 'confirmed', 'preparing', 'ready'].includes(o.status)
      )

      if (soundEnabled && kitchenOrders.length > lastOrderCount && lastOrderCount > 0) {
        try {
          const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgiKu0nGRAMFJ+nK2lcUgxPWuMoqyXbEU0SXeRnq6ZYEQ0SHaQm62YX0M0SHWPm62YXkM0R3SOmqyXXkI0R3OOmayXXUI0RnONl6yWXEE0RXKMlquVW0A0RHGLlKqUWj80RHCKk6mTWj80Q2+Jk6iTWT40Q26IkqeSWD00Qm2HkaaRVzw0QWyGkKWQVjw0QGuFj6SPVTs0QGqEjqOOVDs0P2mDjaKNUzo0P2iCjKGMUjk0PmeBi6CLUTk0PmZ/iqCKUDg0PWV+iZ+JTzg0PGRPGBAA')
          audio.volume = 0.5
          audio.play().catch(() => {})
        } catch {}
      }
      setLastOrderCount(kitchenOrders.length)
      setOrders(kitchenOrders)
    } catch {
      // silent
    }
    setLoading(false)
  }, [selectedStore, soundEnabled, lastOrderCount])

  useEffect(() => {
    fetch('/api/stores').then(r => r.json()).then(d => {
      setStores(d.stores || [])
      if (d.stores?.length > 0) setSelectedStore(d.stores[0].id)
    })
    fetch('/api/auth/me').then(async (r) => {
      const d = await r.json()
      if (r.status === 403) {
        if (d.error === 'STORE_INACTIVE') { router.push('/store-inactive'); return }
      }
      if (d.user) setUser(d.user)
    }).catch(() => {})
    fetch('/api/kitchen-stations').then(r => r.json()).then(d => {
      setStations(d.stations || [])
    }).catch(() => {})
  }, [])

  useEffect(() => {
    fetchOrders()
  }, [fetchOrders])

  const updateItemStatus = async (orderId: string, itemId: string, status: string) => {
    try {
      const res = await fetch(`/api/orders/${orderId}/items/${itemId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      })
      if (!res.ok) throw new Error('Failed')
      const statusLabel = ORDER_ITEM_STATUSES[status]?.label || status
      toast.success(`Item: ${statusLabel}`)
      fetchOrders()
    } catch {
      toast.error('Gagal update status item')
    }
  }

  const bulkUpdateItems = async (order: any, targetStatus: string) => {
    const activeItems = order.items?.filter((i: any) => {
      if (i.status === 'cancelled' || i.status === 'unavailable' || i.status === 'served') return false
      // Filter by selected station — only update items belonging to this station
      if (selectedStation && selectedStation !== 'all') {
        const stId = i.menuItem?.category?.kitchenStationId
        return stId === selectedStation
      }
      return true
    }) || []

    for (const item of activeItems) {
      try {
        await fetch(`/api/orders/${order.id}/items/${item.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status: targetStatus }),
        })
      } catch {}
    }
    toast.success(`Semua item → ${ORDER_ITEM_STATUSES[targetStatus]?.label || targetStatus}`)
    fetchOrders()
  }

  const getTimeElapsed = (createdAt: string) => {
    const diff = Math.floor((Date.now() - new Date(createdAt).getTime()) / 60000)
    if (diff < 1) return 'Baru saja'
    if (diff < 60) return `${diff} mnt`
    return `${Math.floor(diff / 60)}j ${diff % 60}m`
  }

  // Filter orders by selected station + derive per-station status
  const filteredOrders = useMemo(() => {
    if (selectedStation === 'all') return orders
    return orders
      .map(order => {
        const filtered = order.items?.filter((item: any) => {
          const stId = item.menuItem?.category?.kitchenStationId
          return stId === selectedStation
        })
        if (!filtered || filtered.length === 0) return null
        // Derive effective status from THIS station's items only
        const activeItems = filtered.filter(
          (i: any) => i.status !== 'cancelled' && i.status !== 'unavailable'
        )
        let effectiveStatus = order.status
        if (activeItems.length > 0) {
          const statuses = activeItems.map((i: any) => i.status)
          if (statuses.every((s: string) => s === 'served')) effectiveStatus = 'ready'
          else if (statuses.every((s: string) => s === 'ready' || s === 'served')) effectiveStatus = 'ready'
          else if (statuses.some((s: string) => s === 'preparing')) effectiveStatus = 'preparing'
          else if (statuses.every((s: string) => s === 'pending')) effectiveStatus = 'pending'
          else effectiveStatus = 'preparing'
        }
        return { ...order, items: filtered, effectiveStatus }
      })
      .filter(Boolean)
  }, [orders, selectedStation])

  const getEffectiveStatus = (o: any) => o.effectiveStatus || o.status
  const pendingOrders = filteredOrders.filter(o => getEffectiveStatus(o) === 'pending')
  const confirmedOrders = filteredOrders.filter(o => getEffectiveStatus(o) === 'confirmed')
  const preparingOrders = filteredOrders.filter(o => getEffectiveStatus(o) === 'preparing')
  const readyOrders = filteredOrders.filter(o => getEffectiveStatus(o) === 'ready')

  // Update URL when station changes
  const handleStationChange = (stationId: string) => {
    setSelectedStation(stationId)
    const url = new URL(window.location.href)
    if (stationId === 'all') url.searchParams.delete('station')
    else url.searchParams.set('station', stationId)
    router.replace(url.pathname + url.search)
  }

  if (featureLoading || loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-900">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
      </div>
    )
  }

  if (!featureAllowed) {
    return <FeatureBlockedPage featureLabel="Kitchen Display" />
  }

  return (
    <div className="h-screen flex flex-col bg-gray-900 text-white">
      {/* Top Bar */}
      <header className="bg-gray-800 border-b border-gray-700 px-4 py-3 flex items-center justify-between flex-shrink-0">
        <div className="flex items-center gap-3">
          <button onClick={() => router.push('/dashboard')} className="text-gray-400 hover:text-white p-1">
            <ArrowLeft className="w-5 h-5" />
          </button>
          <ChefHat className="w-6 h-6 text-primary-500" />
          <h1 className="text-lg font-bold">Kitchen Display</h1>
          <span className="text-sm text-gray-400">|</span>
          <span className="text-sm text-gray-400">{filteredOrders.length} pesanan aktif</span>
        </div>
        <div className="flex items-center gap-3">
          <select
            className="bg-gray-700 border border-gray-600 text-white text-sm rounded-lg px-3 py-1.5"
            value={selectedStore}
            onChange={(e) => setSelectedStore(e.target.value)}
          >
            {stores.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
          <button
            onClick={() => setSoundEnabled(!soundEnabled)}
            className={`p-2 rounded-lg ${soundEnabled ? 'bg-primary-600 text-white' : 'bg-gray-700 text-gray-400'}`}
            title={soundEnabled ? 'Suara aktif' : 'Suara mati'}
          >
            {soundEnabled ? <Volume2 className="w-5 h-5" /> : <VolumeX className="w-5 h-5" />}
          </button>
          <button
            onClick={notifPermission !== 'granted' ? requestPermission : undefined}
            className={`p-2 rounded-lg ${notifPermission === 'granted' ? 'bg-green-600 text-white' : notifPermission === 'denied' ? 'bg-red-900 text-red-400 cursor-not-allowed' : 'bg-yellow-600 text-white animate-pulse'}`}
            title={notifPermission === 'granted' ? 'Notifikasi browser aktif' : notifPermission === 'denied' ? 'Notifikasi browser diblokir. Ubah di pengaturan browser.' : 'Aktifkan notifikasi browser'}
          >
            {notifPermission === 'granted' ? <Bell className="w-5 h-5" /> : <BellRing className="w-5 h-5" />}
          </button>
          {printer.isSupported && printerSettings.thermal_printer_enabled === 'true' && (
            <button
              onClick={printer.isConnected ? printer.disconnect : printer.connect}
              className={`p-2 rounded-lg ${printer.isConnected ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
              title={printer.isConnected ? `Printer: ${printer.deviceName}` : 'Hubungkan Printer'}
            >
              <Printer className="w-5 h-5" />
            </button>
          )}
          <button onClick={() => fetchOrders()} className="p-2 rounded-lg bg-gray-700 text-gray-300 hover:bg-gray-600">
            <RefreshCw className="w-5 h-5" />
          </button>
        </div>
      </header>

      {/* Station Tabs */}
      {stations.length > 0 && (
        <div className="bg-gray-800 border-b border-gray-700 px-4 py-2 flex items-center gap-1.5 overflow-x-auto flex-shrink-0">
          <button
            onClick={() => handleStationChange('all')}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors whitespace-nowrap ${
              selectedStation === 'all'
                ? 'bg-primary-600 text-white'
                : 'bg-gray-700 text-gray-400 hover:text-white hover:bg-gray-600'
            }`}
          >
            Semua
          </button>
          {stations.map((station: any) => (
            <button
              key={station.id}
              onClick={() => handleStationChange(station.id)}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors whitespace-nowrap flex items-center gap-1.5 ${
                selectedStation === station.id
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-700 text-gray-400 hover:text-white hover:bg-gray-600'
              }`}
            >
              {station.color && (
                <span
                  className="w-2.5 h-2.5 rounded-full inline-block flex-shrink-0"
                  style={{ backgroundColor: station.color }}
                />
              )}
              {station.name}
            </button>
          ))}
        </div>
      )}

      {sseStatus === 'disconnected' && (
        <div className="bg-red-600 text-white px-4 py-2 flex items-center justify-center gap-2 text-sm animate-pulse flex-shrink-0">
          <WifiOff className="w-4 h-4" />
          <span>Koneksi terputus. Mencoba menghubungkan kembali...</span>
        </div>
      )}
      {showReconnected && (
        <div className="bg-green-600 text-white px-4 py-2 flex items-center justify-center gap-2 text-sm flex-shrink-0">
          <CheckCircle2 className="w-4 h-4" />
          <span>Terhubung kembali</span>
        </div>
      )}

      {/* Kitchen Columns */}
      <div className="flex-1 overflow-hidden flex">
        <KitchenColumn
          title="Pesanan Baru"
          icon={<AlertCircle className="w-5 h-5" />}
          orders={pendingOrders}
          headerColor="bg-yellow-600"
          onPrint={handlePrintKitchenTicket}
          onItemStatusChange={updateItemStatus}
          onBulkAction={bulkUpdateItems}
          getTimeElapsed={getTimeElapsed}
          columnStatus="pending"
        />
        <KitchenColumn
          title="Dikonfirmasi"
          icon={<Coffee className="w-5 h-5" />}
          orders={confirmedOrders}
          headerColor="bg-blue-600"
          onPrint={handlePrintKitchenTicket}
          onItemStatusChange={updateItemStatus}
          onBulkAction={bulkUpdateItems}
          getTimeElapsed={getTimeElapsed}
          columnStatus="confirmed"
        />
        <KitchenColumn
          title="Sedang Dimasak"
          icon={<ChefHat className="w-5 h-5" />}
          orders={preparingOrders}
          headerColor="bg-indigo-600"
          onPrint={handlePrintKitchenTicket}
          onItemStatusChange={updateItemStatus}
          onBulkAction={bulkUpdateItems}
          getTimeElapsed={getTimeElapsed}
          columnStatus="preparing"
        />
        <KitchenColumn
          title="Siap Disajikan"
          icon={<Package className="w-5 h-5" />}
          orders={readyOrders}
          headerColor="bg-green-600"
          onPrint={handlePrintKitchenTicket}
          onItemStatusChange={updateItemStatus}
          onBulkAction={bulkUpdateItems}
          getTimeElapsed={getTimeElapsed}
          columnStatus="ready"
        />
      </div>

      {filteredOrders.length === 0 && (
        <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
          <div className="text-center text-gray-500">
            <ChefHat className="w-20 h-20 mx-auto mb-4 opacity-30" />
            <p className="text-xl">Tidak ada pesanan aktif</p>
            <p className="text-sm mt-1">Pesanan baru akan muncul otomatis</p>
          </div>
        </div>
      )}
    </div>
  )
}

function KitchenColumn({
  title, icon, orders, headerColor, onPrint, onItemStatusChange, onBulkAction, getTimeElapsed, columnStatus
}: {
  title: string
  icon: React.ReactNode
  orders: any[]
  headerColor: string
  onPrint: (order: any) => void
  onItemStatusChange: (orderId: string, itemId: string, status: string) => void
  onBulkAction: (order: any, targetStatus: string) => void
  getTimeElapsed: (createdAt: string) => string
  columnStatus: string
}) {
  const getItemActions = (itemStatus: string) => {
    switch (columnStatus) {
      case 'pending':
      case 'confirmed':
        if (itemStatus === 'pending') return [
          { status: 'preparing', label: 'Mulai Masak', color: 'bg-indigo-600 hover:bg-indigo-700' },
        ]
        return []
      case 'preparing':
        if (itemStatus === 'preparing') return [
          { status: 'ready', label: 'Siap!', color: 'bg-green-600 hover:bg-green-700' },
        ]
        if (itemStatus === 'pending') return [
          { status: 'preparing', label: 'Mulai Masak', color: 'bg-indigo-600 hover:bg-indigo-700' },
        ]
        return []
      case 'ready':
        if (itemStatus === 'ready') return [
          { status: 'served', label: 'Disajikan', color: 'bg-teal-600 hover:bg-teal-700' },
        ]
        return []
      default:
        return []
    }
  }

  const getBulkAction = () => {
    switch (columnStatus) {
      case 'pending':
      case 'confirmed':
        return { status: 'preparing', label: 'Semua Mulai Masak' }
      case 'preparing':
        return { status: 'ready', label: 'Semua Siap!' }
      case 'ready':
        return { status: 'served', label: 'Semua Disajikan' }
      default:
        return null
    }
  }

  const bulkAction = getBulkAction()

  return (
    <div className="flex-1 flex flex-col border-r border-gray-700 last:border-r-0 min-w-0">
      <div className={`${headerColor} px-4 py-2.5 flex items-center justify-between flex-shrink-0`}>
        <div className="flex items-center gap-2 text-sm font-semibold">
          {icon} {title}
        </div>
        <span className="bg-white/20 px-2 py-0.5 rounded-full text-xs font-bold">{orders.length}</span>
      </div>
      <div className="flex-1 overflow-y-auto p-2 space-y-2">
        {orders.map((order: any) => (
          <div key={order.id} className="bg-gray-800 rounded-lg border border-gray-700 overflow-hidden">
            <div className="px-3 py-2 flex items-center justify-between border-b border-gray-700">
              <div>
                <span className="font-mono text-sm font-bold text-primary-400">{order.orderNumber}</span>
                <div className="flex items-center gap-2 text-xs text-gray-400 mt-0.5">
                  {order.table && <span>Meja {order.table.number}</span>}
                  {order.customerName && <span>• {order.customerName}</span>}
                  <span className={`px-1.5 py-0.5 rounded text-xs font-medium ${order.orderType === 'takeaway' ? 'bg-purple-900 text-purple-300' : 'bg-gray-700 text-gray-300'}`}>
                    {order.orderType === 'takeaway' ? 'TAKEAWAY' : 'DINE-IN'}
                  </span>
                </div>
              </div>
              <div className="flex items-center gap-1 text-xs text-gray-400">
                <Clock className="w-3.5 h-3.5" />
                {getTimeElapsed(order.createdAt)}
              </div>
            </div>
            {/* Per-item controls */}
            <div className="px-3 py-2 space-y-1.5">
              {order.items?.map((item: any) => {
                const isInactive = item.status === 'cancelled' || item.status === 'unavailable' || item.status === 'served'
                const itemActions = getItemActions(item.status)
                const itemStatusInfo = ORDER_ITEM_STATUSES[item.status]

                return (
                  <div key={item.id} className={isInactive ? 'opacity-40' : ''}>
                    <div className="flex items-start gap-2">
                      <span className="bg-primary-600 text-white w-5 h-5 rounded flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">
                        {item.quantity}
                      </span>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-1.5 flex-wrap">
                          <span className={`text-sm ${isInactive ? 'line-through text-gray-500' : 'text-gray-200'}`}>
                            {item.menuItem?.name}
                          </span>
                          {itemStatusInfo && item.status !== 'pending' && (
                            <span className={`text-[10px] px-1 py-0.5 rounded font-medium ${
                              item.status === 'preparing' ? 'bg-indigo-900 text-indigo-300' :
                              item.status === 'ready' ? 'bg-green-900 text-green-300' :
                              item.status === 'served' ? 'bg-teal-900 text-teal-300' :
                              item.status === 'cancelled' ? 'bg-red-900 text-red-300' :
                              item.status === 'unavailable' ? 'bg-gray-700 text-gray-400' :
                              'bg-gray-700 text-gray-300'
                            }`}>
                              {itemStatusInfo.label}
                            </span>
                          )}
                        </div>
                        {item.selectedVariants?.length > 0 && (
                          <span className="text-xs text-gray-400">({item.selectedVariants.map((v: any) => v.name).join(', ')})</span>
                        )}
                        {item.notes && (
                          <p className="text-xs text-yellow-400 mt-0.5 italic">&bull; {item.notes}</p>
                        )}
                      </div>
                      {!isInactive && (
                        <div className="flex items-center gap-1 flex-shrink-0">
                          {itemActions.map((action) => (
                            <button
                              key={action.status}
                              onClick={() => onItemStatusChange(order.id, item.id, action.status)}
                              className={`${action.color} text-white text-[10px] px-2 py-1 rounded font-medium`}
                              title={action.label}
                            >
                              {action.label}
                            </button>
                          ))}
                          {item.status !== 'ready' && item.status !== 'served' && (
                            <button
                              onClick={() => onItemStatusChange(order.id, item.id, 'unavailable')}
                              className="bg-gray-600 hover:bg-gray-500 text-gray-300 text-[10px] px-1.5 py-1 rounded"
                              title="Tidak Tersedia"
                            >
                              <Ban className="w-3 h-3" />
                            </button>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                )
              })}
              {order.notes && (
                <p className="text-xs text-yellow-400 mt-1 bg-yellow-900/30 px-2 py-1 rounded">
                  {order.notes}
                </p>
              )}
            </div>
            <div className="px-3 pb-2 flex gap-2">
              <button
                onClick={() => onPrint(order)}
                className="py-2 px-3 rounded-lg text-sm font-semibold bg-gray-700 hover:bg-gray-600 text-gray-200 transition-colors"
                title="Cetak tiket dapur"
              >
                <Printer className="w-4 h-4" />
              </button>
              {bulkAction && (
                <button
                  onClick={() => onBulkAction(order, bulkAction.status)}
                  className="flex-1 py-2 rounded-lg text-sm font-semibold bg-primary-600 hover:bg-primary-700 text-white transition-colors"
                >
                  {bulkAction.label} →
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
