import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast'
import client from '../api/client'

function relativeTime(isoStr) {
  if (!isoStr) return ''
  const diffMs = Date.now() - new Date(isoStr).getTime()
  const diffMins = Math.floor(diffMs / 60000)
  if (diffMins < 1) return 'μόλις τώρα'
  if (diffMins < 60) return `πριν ${diffMins}λ`
  const h = Math.floor(diffMins / 60)
  if (h < 24) return `πριν ${h}ω`
  return `πριν ${Math.floor(h / 24)}μ`
}

function FlagsDetailModal({ flags, tableName, onClose }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 9999,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }} onClick={onClose}>
      <div style={{
        background: 'white', borderRadius: 16, width: '100%', maxWidth: 360,
        padding: 20, boxShadow: '0 16px 48px rgba(0,0,0,0.18)',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#111315' }}>Σημαίες — {tableName}</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#8a9099' }}>✕</button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {flags.map(f => (
            <div key={f.id} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 12px', borderRadius: 10,
              background: (f.color || '#6b7280') + '11',
              border: `1px solid ${(f.color || '#6b7280')}33`,
            }}>
              {f.emoji && <span style={{ fontSize: 20 }}>{f.emoji}</span>}
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: f.color || '#374151' }}>{f.name}</div>
                {f.assigned_at && (
                  <div style={{ fontSize: 11, color: '#8a9099', marginTop: 1 }}>{relativeTime(f.assigned_at)}</div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

const API_URL = import.meta.env.VITE_API_URL || ''

const STATUS_OPTIONS = [
  { value: 'open',           label: 'Ανοιχτά' },
  { value: 'partially_paid', label: 'Μερική πληρωμή' },
  { value: 'paid',           label: 'Πλήρως πληρωμένο' },
  { value: 'free',           label: 'Ελεύθερα' },
]

const COLORS = {
  open: {
    label: 'Ανοιχτό',
    tint: '#eef7f0', tintStrong: '#d7ecdc',
    accent: '#2f9e5e', ink: '#1f7042',
  },
  partially_paid: {
    label: 'Μερική πληρ.',
    tint: '#f4eefb', tintStrong: '#e3d4f3',
    accent: '#7a44c9', ink: '#57309a',
  },
  paid: {
    label: 'Πλήρως πληρωμένο',
    tint: '#eff6ff', tintStrong: '#dbeafe',
    accent: '#2563eb', ink: '#1d4ed8',
  },
  free: {
    label: 'Ελεύθερο',
    tint: '#f4f4f2', tintStrong: '#dfe2e6',
    accent: '#8a9099', ink: '#5a6169',
  },
}

function formatEuro(n) {
  return '€' + parseFloat(n).toFixed(2)
}

function formatDuration(openedAt) {
  const mins = Math.floor((Date.now() - new Date(openedAt).getTime()) / 60000)
  if (mins < 60) return `${mins}m`
  const h = Math.floor(mins / 60)
  const m = mins % 60
  return m === 0 ? `${h}h` : `${h}h ${m}m`
}

function occupiedMinsFromDate(openedAt) {
  return Math.floor((Date.now() - new Date(openedAt).getTime()) / 60000)
}

function orderTotal(items = []) {
  return items
    .filter(i => i.status !== 'cancelled')
    .reduce((s, i) => s + i.unit_price * i.quantity, 0)
}

function avatarColor(name) {
  const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
  let h = 0
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
  return palette[h % palette.length]
}

function WaiterBubble({ waiter, size = 26 }) {
  if (waiter.avatarUrl) {
    return (
      <img src={waiter.avatarUrl} alt={waiter.name}
        style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0, boxShadow: '0 0 0 2px var(--cardBg, white)' }}
      />
    )
  }
  const parts = waiter.name.trim().split(' ')
  const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: avatarColor(waiter.name), color: 'white',
      fontSize: size * 0.42, fontWeight: 600,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0, boxShadow: '0 0 0 2px var(--cardBg, white)',
    }}>{initials}</div>
  )
}

// ─── Quick action modal ────────────────────────────────────────────────────────

function QuickActionModal({ table, order, flagDefs, currentFlags, waiters, templates, onClose, onDone }) {
  const qc = useQueryClient()
  const [selectedFlagIds, setSelectedFlagIds] = useState((currentFlags || []).map(f => f.id))
  const [notifyMsg, setNotifyMsg] = useState('')
  const [notifyAll, setNotifyAll] = useState(true)
  const [notifyWaiters, setNotifyWaiters] = useState(false)
  const [sending, setSending] = useState(false)

  const setFlagsMut = useMutation({
    mutationFn: () => client.put(`/api/flags/table/${table.id}`, { flag_ids: selectedFlagIds }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['flag-assignments'] }),
  })

  function toggleFlag(id) {
    setSelectedFlagIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  async function save() {
    setSending(true)
    try {
      await setFlagsMut.mutateAsync()
      if (notifyWaiters && notifyMsg.trim() && order) {
        const waiterIds = notifyAll ? [] : order.waiters.map(w => w.waiter_id)
        await client.post('/api/messages/send', {
          body: notifyMsg.trim(),
          target_waiter_ids: waiterIds,
          table_ids: [table.id],
        })
        toast.success('Σημαίες + ειδοποίηση εστάλη!')
      } else {
        toast.success('Σημαίες ενημερώθηκαν')
      }
      onDone()
      onClose()
    } catch {
      toast.error('Σφάλμα')
    } finally {
      setSending(false)
    }
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 9999,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }} onClick={onClose}>
      <div style={{
        background: 'white', borderRadius: 20, width: '100%', maxWidth: 460,
        padding: 24, boxShadow: '0 24px 64px rgba(0,0,0,0.22)',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>⚡ {table.label || `T${table.number}`}</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#8a9099' }}>✕</button>
        </div>

        <div style={{ fontSize: 12, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>Σημαίες</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 20 }}>
          {flagDefs.map(f => {
            const sel = selectedFlagIds.includes(f.id)
            return (
              <button key={f.id} onClick={() => toggleFlag(f.id)} style={{
                height: 30, padding: '0 12px', borderRadius: 999,
                border: `1.5px solid ${sel ? f.color : '#dfe2e6'}`,
                background: sel ? (f.color + '22') : 'white',
                color: sel ? f.color : '#374151',
                fontSize: 12, fontWeight: sel ? 700 : 500, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 5,
              }}>
                {f.emoji && <span>{f.emoji}</span>}
                {f.name}
              </button>
            )
          })}
        </div>

        {order && (
          <>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, cursor: 'pointer' }}>
              <input type="checkbox" checked={notifyWaiters} onChange={e => setNotifyWaiters(e.target.checked)} />
              <span style={{ fontSize: 13, color: '#374151', fontWeight: 500 }}>Ειδοποίησε τους σερβιτόρους</span>
            </label>

            {notifyWaiters && (
              <div style={{ marginBottom: 16 }}>
                <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                  {templates.slice(0, 4).map(t => (
                    <button key={t.id} onClick={() => setNotifyMsg(t.body)} style={{
                      height: 26, padding: '0 10px', borderRadius: 6,
                      border: `1px solid ${notifyMsg === t.body ? '#3758c9' : '#dfe2e6'}`,
                      background: notifyMsg === t.body ? '#eff3ff' : '#f9fafb',
                      color: notifyMsg === t.body ? '#3758c9' : '#374151',
                      fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
                    }}>{t.body}</button>
                  ))}
                </div>
                <input
                  value={notifyMsg}
                  onChange={e => setNotifyMsg(e.target.value)}
                  placeholder="Ή γράψτε μήνυμα…"
                  style={{ width: '100%', height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit', boxSizing: 'border-box' }}
                />
              </div>
            )}
          </>
        )}

        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={{ height: 36, padding: '0 16px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
          <button onClick={save} disabled={sending} style={{ height: 36, padding: '0 18px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
            {sending ? 'Αποθήκευση…' : 'Αποθήκευση'}
          </button>
        </div>
      </div>
    </div>
  )
}


function FlagPills({ flags, displayMode = 'both', onOverflowClick }) {
  if (flags.length === 0) return null
  const MAX_VISIBLE = 3
  const visible = flags.slice(0, MAX_VISIBLE)
  const overflow = flags.length - MAX_VISIBLE

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden', flexWrap: 'nowrap', minWidth: 0 }}>
      {visible.map(f => (
        <span key={f.id} style={{
          fontSize: 11, fontWeight: 600, borderRadius: 999, padding: '2px 7px',
          background: (f.color || '#6b7280') + '22',
          color: f.color || '#6b7280',
          border: `1px solid ${f.color || '#6b7280'}55`,
          display: 'inline-flex', alignItems: 'center', gap: 3,
          whiteSpace: 'nowrap', flexShrink: 0,
        }}>
          {(displayMode === 'icon' || displayMode === 'both') && f.emoji && <span style={{ fontSize: 12 }}>{f.emoji}</span>}
          {(displayMode === 'text' || displayMode === 'both') && <span>{f.name}</span>}
        </span>
      ))}
      {overflow > 0 && (
        <button
          onClick={e => { e.stopPropagation(); onOverflowClick?.() }}
          title={`+${overflow} ακόμα σημαίες`}
          style={{
            fontSize: 11, fontWeight: 700, borderRadius: 999, padding: '2px 7px',
            background: '#f0f4ff', color: '#3758c9', border: '1px solid #c2cff0',
            whiteSpace: 'nowrap', flexShrink: 0, cursor: 'pointer',
          }}
        >+{overflow}</button>
      )}
    </div>
  )
}

function TableCardV1({ name, status, amount, openedAt, waiters = [], hasPendingPrint = false, flags = [], flagDisplayMode = 'both', onClick, onQuickAction, onFlagsClick }) {
  const s = COLORS[status] || COLORS.free
  const [hover, setHover] = useState(false)
  const [pressed, setPressed] = useState(false)
  const occupiedMins = openedAt ? occupiedMinsFromDate(openedAt) : null

  return (
    <button
      type="button"
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPressed(false) }}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      style={{
        '--cardBg': s.tint,
        position: 'relative', width: '100%', minWidth: 330, height: 200,
        padding: '16px 18px 16px 24px',
        background: s.tint, border: '1px solid ' + s.tintStrong, borderRadius: 14,
        boxShadow: pressed
          ? 'inset 0 2px 4px rgba(16,20,24,0.08)'
          : hover
            ? '0 6px 18px rgba(16,20,24,0.08), 0 2px 4px rgba(16,20,24,0.04)'
            : '0 1px 2px rgba(16,20,24,0.04), 0 1px 1px rgba(16,20,24,0.03)',
        transform: pressed ? 'translateY(1px)' : hover ? 'translateY(-2px)' : 'translateY(0)',
        transition: 'transform 120ms ease, box-shadow 120ms ease',
        cursor: onClick ? 'pointer' : 'default',
        textAlign: 'left', font: 'inherit', color: 'inherit',
        display: 'flex', flexDirection: 'column', outline: 'none', flexShrink: 0,
      }}
    >
      <div style={{
        position: 'absolute', left: 0, top: 0, bottom: 0, width: 6,
        background: s.accent, borderRadius: '14px 0 0 14px',
      }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
        <div style={{
          fontSize: 34, fontWeight: 700, lineHeight: 1, letterSpacing: -0.5,
          color: '#111315', fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
        }}>{name}</div>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          height: 26, padding: '0 10px', borderRadius: 999,
          background: s.accent, color: 'white',
          fontSize: 12, fontWeight: 600, letterSpacing: 0.2,
          whiteSpace: 'nowrap', flexShrink: 0,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'rgba(255,255,255,0.9)' }} />
          {s.label}
        </div>
      </div>
      <div style={{ marginTop: 6, minHeight: 22, display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden' }}>
        {hasPendingPrint && (
          <span style={{
            fontSize: 11, fontWeight: 700, background: '#92400e', color: '#fcd34d',
            borderRadius: 999, padding: '2px 8px', flexShrink: 0,
            display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>⏳</span>
        )}
        <FlagPills
          flags={flags}
          displayMode={flagDisplayMode}
          onOverflowClick={onFlagsClick}
        />
      </div>
      <div style={{ marginTop: 'auto', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, alignItems: 'end' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.6 }}>Total</div>
          <div style={{ fontSize: 22, fontWeight: 600, color: '#111315', marginTop: 2, fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace" }}>
            {amount != null ? formatEuro(amount) : <span style={{ color: '#b8bdc4', letterSpacing: 2 }}>— —</span>}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.6 }}>Time</div>
          <div style={{
            fontSize: 22, marginTop: 2,
            fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
            fontWeight: occupiedMins != null && occupiedMins >= 90 ? 700 : 500,
            color: '#111315',
          }}>
            {openedAt ? formatDuration(openedAt) : <span style={{ color: '#b8bdc4', letterSpacing: 2 }}>— —</span>}
          </div>
        </div>
      </div>
      <div style={{
        marginTop: 12, paddingTop: 10,
        borderTop: '1px solid ' + s.tintStrong,
        height: 36, display: 'flex', alignItems: 'center', gap: 8,
      }}>
        {waiters.length === 0 ? (
          <span style={{ color: '#8a9099', fontSize: 13 }}>Unassigned</span>
        ) : waiters.length >= 3 ? (
          <>
            <div style={{ display: 'flex' }}>
              {waiters.slice(0, 3).map((w, i) => (
                <div key={i} style={{ marginLeft: i === 0 ? 0 : -8 }}>
                  <WaiterBubble waiter={w} size={24} />
                </div>
              ))}
            </div>
            <span style={{
              fontSize: 13, fontWeight: 600, color: '#2b2f33',
              background: 'white', border: '1px solid #dfe2e6',
              borderRadius: 999, padding: '2px 8px',
            }}>Multiple ({waiters.length})</span>
          </>
        ) : (
          waiters.map((w, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <WaiterBubble waiter={w} size={24} />
              <span style={{ fontSize: 14, color: '#2b2f33', fontWeight: 500 }}>{w.shortName}</span>
            </div>
          ))
        )}
        {onQuickAction && (
          <button
            onClick={e => { e.stopPropagation(); onQuickAction() }}
            title="Γρήγορες ενέργειες"
            style={{
              marginLeft: 'auto', width: 28, height: 28, borderRadius: 8, flexShrink: 0,
              border: '1px solid ' + s.tintStrong, background: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 14, cursor: 'pointer', color: '#5a6169',
            }}
          >⚡</button>
        )}
      </div>
    </button>
  )
}

// ─── Multi-select dropdown ─────────────────────────────────────────────────────

function MultiSelectDropdown({ label, options, selected, onChange, allLabel = 'Όλα' }) {
  const [open, setOpen] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    function handleClick(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false)
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [])

  const allSelected = selected.length === 0
  const displayLabel = allSelected
    ? allLabel
    : selected.length === 1
      ? options.find(o => o.value === selected[0])?.label ?? selected[0]
      : `${selected.length} επιλεγμένα`

  function toggle(value) {
    if (selected.includes(value)) {
      onChange(selected.filter(v => v !== value))
    } else {
      onChange([...selected, value])
    }
  }

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          height: 36, padding: '0 14px',
          borderRadius: 8, border: '1px solid #dfe2e6',
          background: allSelected ? 'white' : '#f0f4ff',
          color: allSelected ? '#374151' : '#3758c9',
          fontSize: 13, fontWeight: allSelected ? 500 : 600,
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
          whiteSpace: 'nowrap', fontFamily: 'inherit',
          boxShadow: open ? '0 0 0 2px #c2cff0' : 'none',
          transition: 'box-shadow 100ms',
        }}
      >
        <span style={{ fontSize: 11, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginRight: 2 }}>{label}</span>
        {displayLabel}
        <span style={{ fontSize: 10, color: '#8a9099', marginLeft: 2 }}>{open ? '▲' : '▼'}</span>
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: '100%', left: 0, marginTop: 6, zIndex: 100,
          background: 'white', border: '1px solid #dfe2e6', borderRadius: 12,
          boxShadow: '0 8px 24px rgba(16,20,24,0.12)',
          minWidth: 180, overflow: 'hidden',
        }}>
          {/* All option */}
          <button
            onClick={() => { onChange([]); setOpen(false) }}
            style={{
              width: '100%', padding: '10px 14px',
              display: 'flex', alignItems: 'center', gap: 10,
              background: allSelected ? '#f0f4ff' : 'white',
              border: 'none', cursor: 'pointer', textAlign: 'left',
              fontSize: 13, fontWeight: allSelected ? 700 : 400,
              color: allSelected ? '#3758c9' : '#374151',
              fontFamily: 'inherit',
              borderBottom: '1px solid #f4f4f2',
            }}
          >
            <span style={{
              width: 16, height: 16, borderRadius: 4,
              border: '1.5px solid ' + (allSelected ? '#3758c9' : '#dfe2e6'),
              background: allSelected ? '#3758c9' : 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              {allSelected && <span style={{ color: 'white', fontSize: 10, fontWeight: 700 }}>✓</span>}
            </span>
            {allLabel}
          </button>
          {options.map(opt => {
            const checked = selected.includes(opt.value)
            return (
              <button
                key={opt.value}
                onClick={() => toggle(opt.value)}
                style={{
                  width: '100%', padding: '10px 14px',
                  display: 'flex', alignItems: 'center', gap: 10,
                  background: checked ? '#f9f5ff' : 'white',
                  border: 'none', cursor: 'pointer', textAlign: 'left',
                  fontSize: 13, fontWeight: checked ? 600 : 400,
                  color: checked ? '#57309a' : '#374151',
                  fontFamily: 'inherit',
                  borderBottom: '1px solid #f9f9f8',
                }}
              >
                <span style={{
                  width: 16, height: 16, borderRadius: 4,
                  border: '1.5px solid ' + (checked ? '#7a44c9' : '#dfe2e6'),
                  background: checked ? '#7a44c9' : 'white',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  {checked && <span style={{ color: 'white', fontSize: 10, fontWeight: 700 }}>✓</span>}
                </span>
                {opt.label}
              </button>
            )
          })}
        </div>
      )}
    </div>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function TablesPage() {
  const [statusFilter, setStatusFilter] = useState([])
  const [zoneFilter, setZoneFilter] = useState([])
  const [retryingId, setRetryingId] = useState(null)
  const [quickActionTarget, setQuickActionTarget] = useState(null)
  const [flagsDetail, setFlagsDetail] = useState(null) // { flags, tableName }
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const { data: tables = [], isLoading: tablesLoading } = useQuery({
    queryKey: ['tables'],
    queryFn: () => client.get('/api/tables/').then(r => r.data),
    refetchInterval: 5_000,
  })

  const { data: orders = [], isLoading: ordersLoading } = useQuery({
    queryKey: ['orders-active'],
    queryFn: () => client.get('/api/orders/').then(r => r.data),
    refetchInterval: 5_000,
  })

  const { data: flagDefs = [] } = useQuery({
    queryKey: ['flag-defs'],
    queryFn: () => client.get('/api/flags/defs').then(r => r.data),
    staleTime: 30_000,
  })

  const { data: flagAssignments = [] } = useQuery({
    queryKey: ['flag-assignments'],
    queryFn: () => client.get('/api/flags/assignments').then(r => r.data),
    refetchInterval: 10_000,
    staleTime: 8_000,
  })

  // Build map: tableId -> { def, assigned_at }[]
  const flagDefMap = Object.fromEntries(flagDefs.map(f => [f.id, f]))
  const tableFlagsMap = {}
  flagAssignments.forEach(a => {
    if (!tableFlagsMap[a.table_id]) tableFlagsMap[a.table_id] = []
    const def = flagDefMap[a.flag_id]
    if (def) tableFlagsMap[a.table_id].push({ ...def, assigned_at: a.assigned_at })
  })

  const { data: waiters = [] } = useQuery({
    queryKey: ['waiters'],
    queryFn: () => client.get('/api/waiters/').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: quickTemplates = [] } = useQuery({
    queryKey: ['quick-templates'],
    queryFn: () => client.get('/api/messages/templates').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: groups = [] } = useQuery({
    queryKey: ['table-groups'],
    queryFn: () => client.get('/api/tables/groups').then(r => r.data),
    staleTime: 60_000,
  })

  const { data: posSettings } = useQuery({
    queryKey: ['pos-settings'],
    queryFn: () => client.get('/api/settings/').then(r => r.data),
    staleTime: 30_000,
  })
  const flagDisplayMode = posSettings?.['flags.display_mode']?.value ?? 'both'

  const waiterMap = Object.fromEntries(waiters.map(w => {
    const name = w.full_name || w.nickname || w.username
    const shortName = w.nickname || (w.full_name ? w.full_name.split(' ')[0] : w.username)
    const avatarUrl = w.avatar_url ? API_URL + w.avatar_url : null
    return [w.id, { name, shortName, avatarUrl }]
  }))

  const tableCards = tables.map(table => {
    const order = orders.find(o =>
      o.table_id === table.id && ['open', 'partially_paid', 'paid'].includes(o.status)
    )
    const tableStatus = order ? order.status : 'free'
    const hasPendingPrint = order ? order.items.some(i => i.status === 'active' && !i.printed) : false
    const tableFlags = tableFlagsMap[table.id] || []
    return { table, order, tableStatus, hasPendingPrint, tableFlags }
  })

  const pendingPrintOrders = tableCards.filter(c => c.hasPendingPrint)

  async function retrySingleOrder(orderId) {
    setRetryingId(orderId)
    try {
      const res = await client.post(`/api/orders/${orderId}/retry-print`)
      const results = res.data.print_results ?? []
      const allOk = results.length === 0 || results.every(r => r.success)
      if (allOk) toast.success('Εκτυπώθηκε επιτυχώς')
      else {
        const failed = results.filter(r => !r.success).map(r => r.printer_name).join(', ')
        toast.error(`Αποτυχία: ${failed}`)
      }
      queryClient.invalidateQueries({ queryKey: ['orders-active'] })
    } catch {
      toast.error('Σφάλμα επικοινωνίας')
    } finally {
      setRetryingId(null)
    }
  }

  async function retryAllOrders() {
    for (const { order } of pendingPrintOrders) {
      if (order) await retrySingleOrder(order.id)
    }
  }

  // Build zone options from groups + "Χωρίς ζώνη"
  const zoneOptions = [
    ...groups.map(g => ({ value: String(g.id), label: g.name })),
    { value: '__none__', label: 'Χωρίς ζώνη' },
  ]

  // Apply filters
  const filtered = tableCards.filter(c => {
    const statusOk = statusFilter.length === 0 || statusFilter.includes(c.tableStatus)
    let zoneOk = true
    if (zoneFilter.length > 0) {
      const tableGroupId = c.table.group_id ? String(c.table.group_id) : null
      if (zoneFilter.includes('__none__') && zoneFilter.length === 1) {
        zoneOk = !tableGroupId
      } else if (zoneFilter.includes('__none__')) {
        zoneOk = !tableGroupId || zoneFilter.includes(tableGroupId)
      } else {
        zoneOk = tableGroupId !== null && zoneFilter.includes(tableGroupId)
      }
    }
    return statusOk && zoneOk
  })

  if (tablesLoading || ordersLoading) {
    return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
  }

  return (
    <div className="space-y-6">
      {flagsDetail && (
        <FlagsDetailModal
          flags={flagsDetail.flags}
          tableName={flagsDetail.tableName}
          onClose={() => setFlagsDetail(null)}
        />
      )}
      {quickActionTarget && (
        <QuickActionModal
          table={quickActionTarget.table}
          order={quickActionTarget.order}
          flagDefs={flagDefs}
          currentFlags={quickActionTarget.currentFlags}
          waiters={waiters}
          templates={quickTemplates}
          onClose={() => setQuickActionTarget(null)}
          onDone={() => queryClient.invalidateQueries({ queryKey: ['flag-assignments'] })}
        />
      )}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <h1 className="text-xl font-bold text-gray-800">Τραπέζια</h1>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <MultiSelectDropdown
            label="Κατάσταση"
            options={STATUS_OPTIONS}
            selected={statusFilter}
            onChange={setStatusFilter}
            allLabel="Όλες οι καταστάσεις"
          />
          <MultiSelectDropdown
            label="Ζώνη"
            options={zoneOptions}
            selected={zoneFilter}
            onChange={setZoneFilter}
            allLabel="Όλες οι ζώνες"
          />
        </div>
      </div>

      {filtered.length === 0 && (
        <p className="text-center text-gray-400 py-16">Δεν βρέθηκαν τραπέζια.</p>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 16 }}>
        {filtered.map(({ table, order, tableStatus, hasPendingPrint, tableFlags }) => {
          const waiterNames = order
            ? order.waiters.map(w => waiterMap[w.waiter_id] || { name: `#${w.waiter_id}`, shortName: `#${w.waiter_id}`, avatarUrl: null })
            : []
          const amount = order ? orderTotal(order.items) : null

          return (
            <TableCardV1
              key={table.id}
              name={table.label || `T${table.number}`}
              status={tableStatus}
              amount={amount}
              openedAt={order?.opened_at ?? null}
              waiters={waiterNames}
              hasPendingPrint={hasPendingPrint}
              flags={tableFlags}
              flagDisplayMode={flagDisplayMode}
              onClick={order ? () => navigate(`/orders/${order.id}`) : undefined}
              onQuickAction={() => setQuickActionTarget({ table, order, currentFlags: tableFlags })}
              onFlagsClick={tableFlags.length > 3 ? () => setFlagsDetail({ flags: tableFlags, tableName: table.label || `T${table.number}` }) : undefined}
            />
          )
        })}
      </div>

      {pendingPrintOrders.length > 0 && (
        <div className="bg-white rounded-2xl border border-orange-200 shadow-sm overflow-hidden">
          <div className="flex items-center justify-between px-5 py-4 border-b border-orange-100" style={{ background: '#fff7ed' }}>
            <div className="flex items-center gap-3">
              <span style={{ fontSize: 20 }}>⏳</span>
              <div>
                <h2 className="text-base font-bold text-orange-900">Εκκρεμείς Εκτυπώσεις</h2>
                <p className="text-xs text-orange-700 mt-0.5">
                  {pendingPrintOrders.length} παραγγελί{pendingPrintOrders.length !== 1 ? 'ες' : 'α'} δεν έχ{pendingPrintOrders.length !== 1 ? 'ουν' : 'ει'} σταλεί στην κουζίνα/μπαρ
                </p>
              </div>
            </div>
            <button
              className="btn btn-primary text-sm"
              style={{ background: '#c2410c', borderColor: '#c2410c' }}
              onClick={retryAllOrders}
              disabled={retryingId !== null}
            >
              {retryingId !== null ? 'Αποστολή…' : 'Αποστολή Όλων'}
            </button>
          </div>
          <div className="divide-y divide-orange-50">
            {pendingPrintOrders.map(({ table, order }) => {
              const unprinted = order.items.filter(i => i.status === 'active' && !i.printed)
              const tableName = table.label || `T${table.number}`
              return (
                <div key={order.id} className="flex items-center gap-4 px-5 py-3">
                  <div className="shrink-0 w-10 h-10 rounded-xl flex items-center justify-center font-bold text-sm"
                    style={{ background: '#fff7ed', color: '#c2410c', border: '1px solid #fed7aa' }}>
                    {tableName}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-gray-800">
                      {unprinted.length} αντικείμενο{unprinted.length !== 1 ? 'α' : ''} εκκρεμούν
                    </p>
                    <p className="text-xs text-gray-500 truncate">
                      {unprinted.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <button className="btn btn-secondary text-xs" onClick={() => navigate(`/orders/${order.id}`)}>
                      Λεπτομέρειες
                    </button>
                    <button
                      className="btn btn-primary text-xs"
                      style={{ background: '#c2410c', borderColor: '#c2410c' }}
                      onClick={() => retrySingleOrder(order.id)}
                      disabled={retryingId === order.id}
                    >
                      {retryingId === order.id ? '…' : 'Εκτύπωση'}
                    </button>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}
