import { useEffect, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { ShoppingBag, Radio, Truck, Store as StoreIcon } from 'lucide-react'
import { getAdminOrders, getStores, setOrderStatus } from '../api/client'
import StatusBadge from '../components/StatusBadge'
import { money } from '../store/shop'

const FLOW: Record<string, string> = { PAID: 'PREPARING', PREPARING: 'SHIPPED', SHIPPED: 'DELIVERED' }

export default function Orders() {
  const qc = useQueryClient()
  const [status, setStatus] = useState('')
  const [live, setLive] = useState<any[]>([])
  const [connected, setConnected] = useState(false)
  const wsRef = useRef<WebSocket | null>(null)

  const { data: orders } = useQuery({ queryKey: ['admin-orders', status], queryFn: () => getAdminOrders(status, 100) })
  const { data: stores } = useQuery({ queryKey: ['ord-stores'], queryFn: () => getStores(false) })

  // 실시간 주문 알림 WebSocket (관리자 라이브 대시보드)
  useEffect(() => {
    try {
      const proto = location.protocol === 'https:' ? 'wss' : 'ws'
      const ws = new WebSocket(`${proto}://${location.host}/ws/mall/orders`)
      wsRef.current = ws
      ws.onopen = () => setConnected(true)
      ws.onclose = () => setConnected(false)
      ws.onmessage = (ev) => {
        try {
          const m = JSON.parse(ev.data)
          setLive(prev => [m, ...prev].slice(0, 12))
          if (m.event === 'ORDER_NEW') qc.invalidateQueries({ queryKey: ['admin-orders'] })
        } catch { /* noop */ }
      }
      return () => ws.close()
    } catch { setConnected(false) }
  }, [])

  const advance = async (o: any) => { const next = FLOW[o.status]; if (!next) return; await setOrderStatus(o.id, next).catch(() => {}); qc.invalidateQueries({ queryKey: ['admin-orders'] }) }
  const storeName = (id: number) => stores?.find((s: any) => s.id === id)?.code || `#${id}`
  const list = orders || []

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <div className="flex items-center gap-2"><ShoppingBag className="text-brand" size={22} /><h1 className="text-xl font-bold">Orders (Live)</h1></div>
        <div className="flex items-center gap-3">
          <span className={`flex items-center gap-1.5 text-xs ${connected ? 'text-emerald-400' : 'text-slate-500'}`}><Radio size={13} /> {connected ? 'Connected' : 'Offline'}</span>
          <select value={status} onChange={e => setStatus(e.target.value)} className="bg-card border border-edge rounded-lg px-3 py-2 text-sm">
            <option value="">All</option>
            {['PENDING', 'PAID', 'PREPARING', 'SHIPPED', 'DELIVERED', 'CONFIRMED', 'CANCELLED'].map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      {!!live.length && (
        <div className="bg-card border border-edge rounded-xl p-4 mb-5">
          <div className="text-xs text-slate-400 mb-2 flex items-center gap-1.5"><Radio size={12} className="text-brand" /> Live Events</div>
          <div className="flex flex-wrap gap-2">
            {live.map((m, i) => (
              <span key={i} className="text-xs bg-panel border border-edge rounded-full px-3 py-1 text-slate-300">
                {m.event === 'ORDER_NEW' ? '🆕' : '🔄'} {m.orderNo} · {storeName(m.storeId)} · {m.status} {m.payAmount ? `· ${money(m.payAmount)}` : ''}
              </span>
            ))}
          </div>
        </div>
      )}

      <div className="bg-card border border-edge rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead><tr className="text-slate-400 text-xs border-b border-edge bg-panel">
            <th className="text-left p-3">Order No.</th><th className="text-left">Store</th><th className="text-left">Fulfillment</th>
            <th className="text-left">Schedule</th><th className="text-left">Recipient</th><th className="text-right">Amount</th><th className="text-center">Status</th><th className="text-center">Actions</th>
          </tr></thead>
          <tbody>
            {list.map((o: any) => (
              <tr key={o.id} className="border-b border-edge/50 hover:bg-panel/50">
                <td className="p-3 font-mono text-xs text-brand">{o.orderNo || `#${o.id}`}</td>
                <td className="text-slate-400">{storeName(o.storeId)}</td>
                <td>{o.fulfillmentType === 'PICKUP' ? <span className="flex items-center gap-1 text-xs"><StoreIcon size={12} /> 픽업</span> : <span className="flex items-center gap-1 text-xs"><Truck size={12} /> 배송</span>}</td>
                <td className="text-slate-400 text-xs">{o.scheduledDate} {o.slotLabel}</td>
                <td className="text-slate-400">{o.receiverName || '-'}</td>
                <td className="text-right">{money(o.payAmount ?? o.totalAmount)}</td>
                <td className="text-center"><StatusBadge status={o.status} /></td>
                <td className="text-center">
                  {FLOW[o.status] && <button onClick={() => advance(o)} className="text-xs bg-brand text-ink font-semibold px-2.5 py-1 rounded">→ {FLOW[o.status]}</button>}
                </td>
              </tr>
            ))}
            {!list.length && <tr><td colSpan={8} className="text-center text-slate-500 py-8">주문이 없습니다.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
