'use client'

import { useEffect, useState, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import {
  ArrowLeft, Bell, BellRing, Check, Package, CreditCard, HandCoins,
  Clock, RefreshCw, User, MapPin, Volume2, VolumeX, X, CheckCircle2, WifiOff
} from 'lucide-react'
import { formatCurrency } from '@/lib/utils'
import toast from 'react-hot-toast'
import { useSSE } from '@/hooks/useSSE'
import { useBrowserNotification } from '@/hooks/useBrowserNotification'

export default function WaiterPage() {
  const router = useRouter()
  const [stores, setStores] = useState<any[]>([])
  const [selectedStore, setSelectedStore] = useState('')
  const [readyOrders, setReadyOrders] = useState<any[]>([])
  const [notifications, setNotifications] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [soundEnabled, setSoundEnabled] = useState(true)
  const [lastNotifCount, setLastNotifCount] = useState(0)
  const { permission: notifPermission, requestPermission, notify } = useBrowserNotification()
  const [activeTab, setActiveTab] = useState<'ready' | 'calls' | 'payment'>('ready')

  const { status: sseStatus, showReconnected } = useSSE({
    storeId: selectedStore,
    onOrderCreated: (data: any) => {
      fetchData()
      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: () => fetchData(),
    onNotificationCreated: (data: any) => {
      fetchData()
      notify(data.title || '🔔 Notifikasi Baru', {
        body: data.message || '',
        tag: `notif-${data.notificationId || Date.now()}`,
      })
    },
    enabled: !!selectedStore,
  })

  const fetchData = useCallback(async () => {
    try {
      const params = new URLSearchParams()
      if (selectedStore) params.set('storeId', selectedStore)

      const [ordersRes, notifsRes] = await Promise.all([
        fetch(`/api/orders?${params}`).then(r => r.json()),
        fetch(`/api/notifications?${params}&unreadOnly=true`).then(r => r.json()),
      ])

      const ready = (ordersRes.orders || []).filter((o: any) => o.status === 'ready')
      setReadyOrders(ready)

      const notifs = notifsRes.notifications || []
      setNotifications(notifs)

      // Sound on new notifications
      if (soundEnabled && notifs.length > lastNotifCount && lastNotifCount > 0) {
        try {
          const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgiKu0nGRAMFJ+nK2lcUgxPWuMoqyXbEU0SXeRnq6ZYEQ0SHaQm62YX0M0SHWPm62YXkM0R3SOmqyXXkI0R3OOmayXXUI0RnONl6yWXEE0RXKMlquVW0A0RHGLlKqUWj80RHCKk6mTWj80Q2+Jk6iTWT40Q26IkqeSWD00Qm2HkaaRVzw0QWyGkKWQVjw0QGuFj6SPVTs0QGqEjqOOVDs0P2mDjaKNUzo0P2iCjKGMUjk0PmeBi6CLUTk0PmZ/iqCKUDg0PWV+iZ+JTzg0PGRPGBAA')
          audio.volume = 0.5
          audio.play().catch(() => {})
        } catch {}
      }
      setLastNotifCount(notifs.length)
    } catch {}
    setLoading(false)
  }, [selectedStore, soundEnabled, lastNotifCount])

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

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

  const handleServeOrder = async (orderId: string) => {
    try {
      await fetch(`/api/orders/${orderId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'served' }),
      })
      toast.success('Pesanan ditandai sudah disajikan')
      fetchData()
    } catch {
      toast.error('Gagal update')
    }
  }

  const handleDismissNotification = async (notifId: string) => {
    try {
      await fetch(`/api/notifications/${notifId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isRead: true }),
      })
      fetchData()
    } catch {}
  }

  const callWaiterNotifs = notifications.filter(n => n.type === 'call_waiter')
  const paymentNotifs = notifications.filter(n => n.type === 'call_payment' || n.type === 'payment_request')
  const newOrderNotifs = notifications.filter(n => n.type === 'new_order')

  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 lalu`
    return `${Math.floor(diff / 60)}j ${diff % 60}m lalu`
  }

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

  return (
    <div className="h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
      {/* Top Bar */}
      <header className="bg-white dark:bg-gray-800 border-b border-gray-200 dark: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-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 p-1">
            <ArrowLeft className="w-5 h-5" />
          </button>
          <User className="w-6 h-6 text-primary-600" />
          <h1 className="text-lg font-bold text-gray-900 dark:text-white">Waiter View</h1>
        </div>
        <div className="flex items-center gap-3">
          <select
            className="input-field text-sm w-auto dark:bg-gray-800 dark:border-gray-600 dark:text-white"
            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-100 dark:bg-primary-900/30 text-primary-600' : 'bg-gray-100 dark:bg-gray-700/50 text-gray-400 dark:text-gray-500'}`}
            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-100 dark:bg-green-900/30 text-green-600' : notifPermission === 'denied' ? 'bg-red-100 dark:bg-red-900/30 text-red-400 cursor-not-allowed' : 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 animate-pulse'}`}
            title={notifPermission === 'granted' ? 'Notifikasi browser aktif' : notifPermission === 'denied' ? 'Notifikasi browser diblokir' : 'Aktifkan notifikasi browser'}
          >
            {notifPermission === 'granted' ? <Bell className="w-5 h-5" /> : <BellRing className="w-5 h-5" />}
          </button>
          <button onClick={() => fetchData()} className="p-2 rounded-lg bg-gray-100 dark:bg-gray-700/50 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600">
            <RefreshCw className="w-5 h-5" />
          </button>
        </div>
      </header>

      {/* Tabs */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 flex-shrink-0">
        <div className="flex">
          <button
            onClick={() => setActiveTab('ready')}
            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${
              activeTab === 'ready' ? 'border-primary-600 text-primary-600' : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200'
            }`}
          >
            <Package className="w-4 h-4" /> Siap Antar
            {readyOrders.length > 0 && <span className="bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 px-2 py-0.5 rounded-full text-xs font-bold">{readyOrders.length}</span>}
          </button>
          <button
            onClick={() => setActiveTab('calls')}
            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${
              activeTab === 'calls' ? 'border-primary-600 text-primary-600' : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200'
            }`}
          >
            <BellRing className="w-4 h-4" /> Panggilan
            {callWaiterNotifs.length > 0 && <span className="bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 px-2 py-0.5 rounded-full text-xs font-bold animate-pulse">{callWaiterNotifs.length}</span>}
          </button>
          <button
            onClick={() => setActiveTab('payment')}
            className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${
              activeTab === 'payment' ? 'border-primary-600 text-primary-600' : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200'
            }`}
          >
            <CreditCard className="w-4 h-4" /> Minta Bayar
            {paymentNotifs.length > 0 && <span className="bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-300 px-2 py-0.5 rounded-full text-xs font-bold animate-pulse">{paymentNotifs.length}</span>}
          </button>
        </div>
      </div>

      {/* Connection Status */}
      {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>
      )}

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {activeTab === 'ready' && (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {readyOrders.map(order => (
              <div key={order.id} className="bg-white dark:bg-gray-800 rounded-xl border-2 border-green-200 dark:border-green-800 shadow-sm overflow-hidden">
                <div className="bg-green-50 dark:bg-green-900/30 px-4 py-3 flex items-center justify-between">
                  <div>
                    <span className="font-mono text-sm font-bold text-green-800 dark:text-green-300">{order.orderNumber}</span>
                    <div className="flex items-center gap-2 text-xs text-green-600 dark:text-green-400 mt-0.5">
                      {order.table && <span className="flex items-center gap-1"><MapPin className="w-3 h-3" />Meja {order.table.number}</span>}
                      {order.customerName && <span>• {order.customerName}</span>}
                    </div>
                  </div>
                  <span className={`px-2 py-1 rounded text-xs font-medium ${order.orderType === 'takeaway' ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300' : 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300'}`}>
                    {order.orderType === 'takeaway' ? 'TAKEAWAY' : 'DINE-IN'}
                  </span>
                </div>
                <div className="px-4 py-3 space-y-1">
                  {order.items?.map((item: any, idx: number) => (
                    <div key={idx} className="flex flex-col">
                      <div className="flex items-center gap-2 text-sm">
                        <span className="bg-primary-100 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300 w-5 h-5 rounded flex items-center justify-center text-xs font-bold">{item.quantity}</span>
                        <div>
                          <span className="text-gray-800 dark:text-gray-100">{item.menuItem?.name}</span>
                          {item.selectedVariants?.length > 0 && (
                            <span className="text-xs text-gray-500 dark:text-gray-400 ml-1">({item.selectedVariants.map((v: any) => v.name).join(', ')})</span>
                          )}
                        </div>
                      </div>
                      {item.notes && (
                        <p className="text-xs text-gray-500 dark:text-gray-400 ml-7 italic">&bull; {item.notes}</p>
                      )}
                    </div>
                  ))}
                  {order.notes && (
                    <p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2 bg-yellow-50 dark:bg-yellow-900/30 px-2 py-1 rounded">Catatan: {order.notes}</p>
                  )}
                </div>
                <div className="px-4 pb-3">
                  <button
                    onClick={() => handleServeOrder(order.id)}
                    className="w-full py-2.5 rounded-lg text-sm font-semibold bg-green-600 hover:bg-green-700 text-white transition-colors flex items-center justify-center gap-2"
                  >
                    <CheckCircle2 className="w-4 h-4" /> Tandai Disajikan
                  </button>
                </div>
              </div>
            ))}
            {readyOrders.length === 0 && (
              <div className="col-span-full text-center py-16 text-gray-400 dark:text-gray-500">
                <Package className="w-16 h-16 mx-auto mb-3 opacity-30" />
                <p className="text-lg">Tidak ada pesanan siap antar</p>
                <p className="text-sm">Pesanan dari dapur akan muncul di sini</p>
              </div>
            )}
          </div>
        )}

        {activeTab === 'calls' && (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {callWaiterNotifs.map(notif => (
              <div key={notif.id} className="bg-white dark:bg-gray-800 rounded-xl border-2 border-red-200 dark:border-red-800 shadow-sm p-4 animate-pulse-slow">
                <div className="flex items-start justify-between mb-3">
                  <div className="w-12 h-12 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center">
                    <BellRing className="w-6 h-6 text-red-600 dark:text-red-400" />
                  </div>
                  <span className="text-xs text-gray-400 dark:text-gray-500 flex items-center gap-1">
                    <Clock className="w-3 h-3" /> {getTimeElapsed(notif.createdAt)}
                  </span>
                </div>
                <h3 className="font-bold text-gray-900 dark:text-white text-lg">{notif.title}</h3>
                <p className="text-gray-600 dark:text-gray-300 text-sm mt-1">{notif.message}</p>
                <button
                  onClick={() => handleDismissNotification(notif.id)}
                  className="mt-4 w-full py-2 rounded-lg text-sm font-medium bg-gray-100 dark:bg-gray-700/50 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 flex items-center justify-center gap-2"
                >
                  <Check className="w-4 h-4" /> Selesai
                </button>
              </div>
            ))}
            {callWaiterNotifs.length === 0 && (
              <div className="col-span-full text-center py-16 text-gray-400 dark:text-gray-500">
                <Bell className="w-16 h-16 mx-auto mb-3 opacity-30" />
                <p className="text-lg">Tidak ada panggilan pelayan</p>
              </div>
            )}
          </div>
        )}

        {activeTab === 'payment' && (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {paymentNotifs.map(notif => {
              const data = notif.data ? JSON.parse(notif.data) : {}
              return (
                <div key={notif.id} className="bg-white dark:bg-gray-800 rounded-xl border-2 border-yellow-200 dark:border-yellow-800 shadow-sm p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="w-12 h-12 bg-yellow-100 dark:bg-yellow-900/30 rounded-full flex items-center justify-center">
                      <HandCoins className="w-6 h-6 text-yellow-600 dark:text-yellow-400" />
                    </div>
                    <span className="text-xs text-gray-400 dark:text-gray-500 flex items-center gap-1">
                      <Clock className="w-3 h-3" /> {getTimeElapsed(notif.createdAt)}
                    </span>
                  </div>
                  <h3 className="font-bold text-gray-900 dark:text-white">{notif.title}</h3>
                  <p className="text-gray-600 dark:text-gray-300 text-sm mt-1">{notif.message}</p>
                  {data.total && <p className="text-xl font-bold text-primary-600 mt-2">{formatCurrency(data.total)}</p>}
                  <button
                    onClick={() => handleDismissNotification(notif.id)}
                    className="mt-4 w-full py-2 rounded-lg text-sm font-medium bg-yellow-100 dark:bg-yellow-900/30 hover:bg-yellow-200 dark:hover:bg-yellow-900/50 text-yellow-800 dark:text-yellow-300 flex items-center justify-center gap-2"
                  >
                    <Check className="w-4 h-4" /> Proses di Kasir
                  </button>
                </div>
              )
            })}
            {paymentNotifs.length === 0 && (
              <div className="col-span-full text-center py-16 text-gray-400 dark:text-gray-500">
                <CreditCard className="w-16 h-16 mx-auto mb-3 opacity-30" />
                <p className="text-lg">Tidak ada permintaan pembayaran</p>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
