import { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import client from '../api/client'
import { Percent } from 'lucide-react'
import Badge from '../ui/Badge'
import { ConfirmModal } from '../ui/Modal'
import PaymentMethodModal from '../ui/PaymentMethodModal'
import DesktopOrderingTab from './DesktopOrderingTab'

function PrintOrderModal({ onClose, onPrint, printers }) {
  const [printerId, setPrinterId] = useState(printers[0]?.id ?? '')
  function submit() {
    if (!printerId) { toast.error('Επιλέξτε εκτυπωτή'); return }
    onPrint(Number(printerId))
    onClose()
  }
  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-5">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-bold text-gray-800">Εκτύπωση παραγγελίας</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">✕</button>
        </div>
        <div>
          <label className="label">Εκτυπωτής</label>
          <select className="input w-full" value={printerId} onChange={e => setPrinterId(e.target.value)}>
            <option value="">— Επιλέξτε —</option>
            {printers.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
        </div>
        <div className="flex gap-3">
          <button onClick={onClose} className="btn btn-secondary flex-1">Ακύρωση</button>
          <button onClick={submit} className="btn btn-primary flex-1">Εκτύπωση</button>
        </div>
      </div>
    </div>
  )
}

function effPrice(item) { return (item.unit_price ?? 0) + (item.price_adjustment ?? 0) }
function itemTotal(item) {
  return (effPrice(item) * item.quantity).toFixed(2)
}

const PAYMENT_METHOD_STYLES = {
  cash:     { label: 'ΜΕΤΡΗΤΑ',           color: '#15803d', bg: '#f0fdf4', border: '#86efac' },
  card:     { label: 'ΚΑΡΤΑ',              color: '#1d4ed8', bg: '#eff6ff', border: '#93c5fd' },
  transfer: { label: 'ΤΡΑΠΕΖΙΚΗ',         color: '#6d28d9', bg: '#f5f3ff', border: '#c4b5fd' },
  treat:    { label: 'ΚΕΡΑΣΤΗΚΕ',         color: '#b45309', bg: '#fffbeb', border: '#fcd34d' },
  comp:     { label: 'ΚΕΡΑΣΤΗΚΕ',         color: '#b45309', bg: '#fffbeb', border: '#fcd34d' },
}

function PayMethodChip({ method }) {
  if (!method) return null
  const s = PAYMENT_METHOD_STYLES[method] || { label: method.toUpperCase(), color: '#374151', bg: '#f3f4f6', border: '#d1d5db' }
  return (
    <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 4, background: s.bg, color: s.color, border: `1px solid ${s.border}`, letterSpacing: 0.3 }}>
      {s.label}
    </span>
  )
}

function formatDate(dt) {
  if (!dt) return '—'
  return new Date(dt).toLocaleString('el-GR', { dateStyle: 'short', timeStyle: 'short' })
}

const EVENT_LABELS = {
  ORDER_OPENED: 'Άνοιγμα',
  ITEMS_ADDED: 'Προσθήκη',
  PAYMENT: 'Πληρωμή',
  PAYMENT_OFFLINE: 'Πληρωμή (Offline)',
  ORDER_CLOSED: 'Κλείσιμο',
  ORDER_CANCELLED: 'Ακύρωση',
  ITEM_CANCELLED: 'Ακύρωση αντ.',
}

function AuditTab({ order, waiterMap }) {
  if (!order.audit_logs || order.audit_logs.length === 0) {
    return <p className="py-8 text-center text-gray-400 text-sm">Δεν υπάρχουν εγγραφές.</p>
  }

  const itemsById = Object.fromEntries((order.items || []).map(i => [i.id, i]))

  return (
    <div className="divide-y divide-gray-100">
      {order.audit_logs.map(log => {
        const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true
        const isPayment = log.event_type === 'PAYMENT' || log.event_type === 'PAYMENT_OFFLINE'
        const badgeClass = isDuplicate
          ? 'bg-red-100 text-red-700'
          : isPayment ? 'bg-green-100 text-green-700'
          : log.event_type.includes('CANCEL') ? 'bg-red-100 text-red-600'
          : log.event_type === 'ORDER_CLOSED' ? 'bg-gray-100 text-gray-600'
          : 'bg-blue-100 text-blue-700'
        const displayTime = log.offline_at ? formatDate(log.offline_at) : formatDate(log.created_at)

        // Resolve item names for ITEMS_ADDED and ITEM_CANCELLED events
        let itemNames = []
        if (log.item_ids && (log.event_type === 'ITEMS_ADDED' || log.event_type === 'ITEM_CANCELLED')) {
          try {
            const ids = JSON.parse(log.item_ids)
            itemNames = ids.map(id => {
              const item = itemsById[id]
              return item ? `${item.product?.name ?? `#${item.product_id}`} ×${item.quantity}` : null
            }).filter(Boolean)
          } catch { /* ignore */ }
        }

        return (
          <div key={log.id} className={`flex items-start gap-3 px-4 py-3 ${isDuplicate ? 'bg-red-50' : ''}`}>
            <div className="shrink-0 mt-0.5">
              <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${badgeClass}`}>
                {EVENT_LABELS[log.event_type] ?? log.event_type}
              </span>
              {isDuplicate && (
                <span className="block text-xs text-red-500 font-semibold mt-0.5">ΔΙΠΛΗ</span>
              )}
            </div>
            <div className="flex-1 min-w-0 text-sm text-gray-700">
              <span>{log.waiter_name ?? waiterMap[log.waiter_id] ?? `#${log.waiter_id}`}</span>
              {log.amount != null && (
                <span className={`ml-2 font-semibold ${isDuplicate ? 'text-red-600' : 'text-green-700'}`}>
                  €{log.amount.toFixed(2)}
                </span>
              )}
              {log.payment_method && (
                <span className="ml-1"><PayMethodChip method={log.payment_method} /></span>
              )}
              {itemNames.length > 0 && (
                <div className="mt-1 flex flex-wrap gap-1">
                  {itemNames.map((name, i) => (
                    <span key={i} className="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600">{name}</span>
                  ))}
                </div>
              )}
            </div>
            <div className="text-right shrink-0">
              <span className="text-xs text-gray-400">{displayTime}</span>
              {log.offline_at && (
                <span className="block text-xs text-orange-400">offline</span>
              )}
            </div>
          </div>
        )
      })}
    </div>
  )
}

// ─── Price Events Tab ────────────────────────────────────────────────────────

const PRICE_EVENT_LABELS = {
  modifier_applied:    'Τροποποιητής',
  deal_triggered:      'Προσφορά',
  deal_offer_shown:    'Προσφορά (εμφανίστηκε)',
  deal_offer_accepted: 'Προσφορά (αποδεκτή)',
  deal_offer_dismissed:'Προσφορά (απορρίφθηκε)',
  waiter_discount:     'Έκπτωση σερβιτόρου',
  free_item_added:     'Δωρεάν αντικείμενο',
}

const PRICE_EVENT_COLORS = {
  modifier_applied:    { bg: '#eff6ff', color: '#1d4ed8', border: '#93c5fd' },
  deal_triggered:      { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
  deal_offer_shown:    { bg: '#fefce8', color: '#a16207', border: '#fde68a' },
  deal_offer_accepted: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
  deal_offer_dismissed:{ bg: '#fef2f2', color: '#b91c1c', border: '#fca5a5' },
  waiter_discount:     { bg: '#fdf4ff', color: '#7e22ce', border: '#d8b4fe' },
  free_item_added:     { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
}

function PriceEventsTab({ orderId }) {
  const { data: events = [], isLoading } = useQuery({
    queryKey: ['price-events', orderId],
    queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
  })

  if (isLoading) return (
    <div className="flex justify-center py-16">
      <div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
    </div>
  )

  if (events.length === 0) return (
    <div className="py-16 text-center text-gray-400">
      <Percent className="w-8 h-8 mx-auto mb-2 opacity-30" />
      <p className="text-sm">Δεν υπάρχουν συμβάντα τιμολόγησης για αυτή την παραγγελία.</p>
    </div>
  )

  return (
    <div className="divide-y divide-gray-100">
      {events.map(ev => {
        const label = PRICE_EVENT_LABELS[ev.event_type] ?? ev.event_type
        const style = PRICE_EVENT_COLORS[ev.event_type] ?? { bg: '#f8fafc', color: '#334155', border: '#cbd5e1' }
        const hasDelta = ev.price_before != null && ev.price_after != null
        return (
          <div key={ev.id} className="flex items-start gap-3 px-4 py-3">
            <div className="shrink-0 mt-0.5">
              <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: style.bg, color: style.color, border: `1px solid ${style.border}` }}>
                {label}
              </span>
            </div>
            <div className="flex-1 min-w-0 text-sm">
              <div className="flex flex-wrap gap-x-3 gap-y-0.5 items-baseline">
                {ev.modifier_name && <span className="font-medium text-gray-800">{ev.modifier_name}</span>}
                {ev.deal_name && <span className="font-medium text-gray-800">{ev.deal_name}</span>}
                {ev.applied_by_username && (
                  <span className="text-gray-500 text-xs">από {ev.applied_by_username}</span>
                )}
                {hasDelta && (
                  <span className={`text-xs font-semibold ${ev.delta_amount < 0 ? 'text-green-700' : 'text-red-600'}`}>
                    {ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount?.toFixed(2)}€
                    <span className="font-normal text-gray-400 ml-1">
                      ({ev.price_before?.toFixed(2)} → {ev.price_after?.toFixed(2)})
                    </span>
                  </span>
                )}
              </div>
              {ev.waiter_note && (
                <p className="text-xs text-gray-400 mt-0.5 italic">"{ev.waiter_note}"</p>
              )}
              {ev.conditions_snapshot && Object.keys(ev.conditions_snapshot).length > 0 && (
                <details className="mt-1">
                  <summary className="text-xs text-gray-400 cursor-pointer hover:text-gray-600">Συνθήκες</summary>
                  <pre className="text-[10px] text-gray-500 bg-gray-50 rounded p-2 mt-1 overflow-x-auto">
                    {JSON.stringify(ev.conditions_snapshot, null, 2)}
                  </pre>
                </details>
              )}
            </div>
            <div className="shrink-0 text-right">
              <span className="text-xs text-gray-400">{formatDate(ev.applied_at)}</span>
            </div>
          </div>
        )
      })}
    </div>
  )
}

export default function OrderDetailPage({ orderId: propOrderId, readOnly = false }) {
  const { orderId: paramOrderId } = useParams()
  const orderId = propOrderId ?? paramOrderId
  const navigate = useNavigate()
  const qc = useQueryClient()

  const [tab, setTab] = useState('overview')
  const [confirmAction, setConfirmAction] = useState(null) // { type, payload }
  const [showPrintModal, setShowPrintModal] = useState(false)
  const [payPending, setPayPending] = useState(null) // item_ids waiting for method selection
  const [customerSearch, setCustomerSearch] = useState('')
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false)

  const { data: order, isLoading } = useQuery({
    queryKey: ['order', orderId],
    queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
    enabled: !!orderId,
  })

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

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

  const { data: rawPriceEvents = [] } = useQuery({
    queryKey: ['price-events', orderId],
    queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
    enabled: !!orderId,
    staleTime: 30_000,
  })
  const priceEventsMap = rawPriceEvents.reduce((acc, ev) => {
    if (!acc[ev.order_item_id]) acc[ev.order_item_id] = []
    acc[ev.order_item_id].push(ev)
    return acc
  }, {})

  const printOrder = useMutation({
    mutationFn: (printerId) => client.post(`/api/orders/${orderId}/print`, { printer_id: printerId }),
    onSuccess: () => toast.success('Αποστολή στον εκτυπωτή…'),
    onError: () => toast.error('Σφάλμα εκτύπωσης'),
  })

  const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w.nickname || w.full_name || w.username]))
  const assignedIds = new Set((order?.waiters ?? []).map(w => w.waiter_id))

  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ['order', orderId] })
    qc.invalidateQueries({ queryKey: ['orders-active'] })
  }

  const cancelItem = useMutation({
    mutationFn: (itemId) => client.delete(`/api/orders/${orderId}/items/${itemId}`),
    onSuccess: () => { toast.success('Αντικείμενο ακυρώθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα ακύρωσης αντικειμένου'),
  })

  const cancelOrder = useMutation({
    mutationFn: () => client.delete(`/api/orders/${orderId}`),
    onSuccess: () => { toast.success('Παραγγελία ακυρώθηκε'); navigate('/tables') },
    onError: () => toast.error('Σφάλμα ακύρωσης παραγγελίας'),
  })

  const closeOrder = useMutation({
    mutationFn: () => client.post(`/api/orders/${orderId}/close`),
    onSuccess: () => { toast.success('Παραγγελία έκλεισε'); navigate('/tables') },
    onError: () => toast.error('Σφάλμα κλεισίματος'),
  })

  const assignWaiter = useMutation({
    mutationFn: (waiter_id) => client.put(`/api/orders/${orderId}/assign-waiter`, { waiter_id }),
    onSuccess: () => { toast.success('Σερβιτόρος προστέθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα'),
  })

  const removeWaiter = useMutation({
    mutationFn: (wid) => client.delete(`/api/orders/${orderId}/waiters/${wid}`),
    onSuccess: () => { toast.success('Σερβιτόρος αφαιρέθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα'),
  })

  const { data: customersData = [] } = useQuery({
    queryKey: ['customers', customerSearch],
    queryFn: () => client.get('/api/customers/', { params: customerSearch ? { search: customerSearch } : {} }).then(r => r.data),
    staleTime: 30_000,
    enabled: showCustomerDropdown,
  })

  const assignCustomer = useMutation({
    mutationFn: (customer_id) => client.put(`/api/orders/${orderId}/customer`, { customer_id }),
    onSuccess: (_, customer_id) => { toast.success(customer_id ? 'Πελάτης ανατέθηκε' : 'Πελάτης αφαιρέθηκε'); invalidate(); setShowCustomerDropdown(false); setCustomerSearch('') },
    onError: () => toast.error('Σφάλμα'),
  })

  const payItems = useMutation({
    mutationFn: ({ item_ids, payment_method }) => client.post(`/api/orders/${orderId}/pay`, { item_ids, payment_method }),
    onSuccess: () => { toast.success('Πληρώθηκε'); invalidate() },
    onError: () => toast.error('Σφάλμα πληρωμής'),
  })

  const tabItem = useMutation({
    mutationFn: (itemId) => client.post(`/api/orders/${orderId}/items/${itemId}/tab`),
    onSuccess: () => { toast.success('Αντικείμενο μεταφέρθηκε στην καρτέλα'); invalidate() },
    onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
  })

  function requestPay(item_ids) {
    setPayPending(item_ids)
  }

  function confirmPay(method) {
    if (!payPending) return
    payItems.mutate({ item_ids: payPending, payment_method: method })
    setPayPending(null)
  }

  function handleConfirm() {
    if (!confirmAction) return
    const { type, payload } = confirmAction
    if (type === 'cancelItem') cancelItem.mutate(payload)
    if (type === 'cancelOrder') cancelOrder.mutate()
    if (type === 'closeOrder') closeOrder.mutate()
    setConfirmAction(null)
  }

  if (isLoading) return <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
  if (!order) return <div className="text-center py-16 text-gray-400">Παραγγελία δεν βρέθηκε.</div>

  const activeItems = order.items.filter(i => i.status === 'active')
  const total = order.items
    .filter(i => i.status !== 'cancelled')
    .reduce((s, i) => s + effPrice(i) * i.quantity, 0)

  const isOpen = ['open', 'partially_paid'].includes(order.status)

  // The ordering tab needs full height and no outer padding
  if (tab === 'order') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
        {/* Compact header strip */}
        <div style={{ padding: '10px 20px', borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 16, flexShrink: 0 }}>
          {!propOrderId && (
            <button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
          )}
          <div style={{ fontSize: 14, color: '#64748b' }}>
            Τραπέζι {order.table_name || order.table_id}
          </div>
          <Badge status={order.status} />
          <span style={{ fontSize: 14, fontWeight: 700, color: '#1e293b' }}>€{total.toFixed(2)}</span>
          <div style={{ flex: 1 }} />
          {/* Tab strip inline */}
          <div style={{ display: 'flex', gap: 1, borderBottom: 'none' }}>
            {[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό']].map(([key, label]) => (
              <button key={key} onClick={() => setTab(key)}
                style={{
                  padding: '6px 14px', fontSize: 13, fontWeight: tab === key ? 700 : 500,
                  background: 'none', border: 'none', cursor: 'pointer',
                  borderBottom: `2px solid ${tab === key ? '#4f46e5' : 'transparent'}`,
                  color: tab === key ? '#4f46e5' : '#64748b',
                }}>
                {label}
              </button>
            ))}
          </div>
        </div>
        {/* Full-height ordering terminal */}
        <div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
          <DesktopOrderingTab
            orderId={orderId}
            tableId={order.table_id}
            orderStatus={order.status}
          />
        </div>
      </div>
    )
  }

  return (
    <div className="overflow-y-auto h-full p-6">
    <div className="max-w-3xl mx-auto space-y-6">
      {!propOrderId && (
        <button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
      )}

      {/* Header */}
      <div className="card p-5 flex flex-wrap gap-4 items-start justify-between">
        <div>
          <p className="text-sm text-gray-500">
            Τραπέζι {order.table_name || order.table_id} · Ανοίχτηκε {formatDate(order.opened_at)}
            {order.closed_at && ` · Έκλεισε ${formatDate(order.closed_at)}`}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Badge status={order.status} />
          <span className="text-lg font-bold text-gray-800">€{total.toFixed(2)}</span>
        </div>
      </div>

      {/* Customer assignment */}
      <div className="card p-4">
        <div className="flex items-center justify-between mb-2">
          <h2 className="text-sm font-semibold text-gray-700">Πελάτης</h2>
          {order.customer_id && isOpen && !readOnly && (
            <button
              onClick={() => assignCustomer.mutate(null)}
              className="text-xs text-gray-400 hover:text-red-500"
            >
              Αφαίρεση
            </button>
          )}
        </div>

        {order.customer_id ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: '#eff6ff', borderRadius: 8, border: '1px solid #bfdbfe' }}>
            <span style={{ fontSize: 16 }}>👤</span>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: '#1d4ed8' }}>{order.customer_name || `Πελάτης #${order.customer_id}`}</div>
              {order.customer_phone && <div style={{ fontSize: 11.5, color: '#3b82f6' }}>{order.customer_phone}</div>}
            </div>
          </div>
        ) : isOpen && !readOnly ? (
          <div style={{ position: 'relative' }}>
            {!showCustomerDropdown ? (
              <button
                onClick={() => setShowCustomerDropdown(true)}
                style={{ fontSize: 13, color: '#6b7280', border: '1px dashed #d1d5db', borderRadius: 8, padding: '7px 14px', cursor: 'pointer', background: 'white', width: '100%', textAlign: 'left' }}
              >
                + Ανάθεση πελάτη
              </button>
            ) : (
              <div>
                <input
                  autoFocus
                  value={customerSearch}
                  onChange={e => setCustomerSearch(e.target.value)}
                  placeholder="Αναζήτηση πελάτη…"
                  style={{ width: '100%', padding: '7px 11px', border: '1.5px solid #3b82f6', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }}
                />
                <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, background: 'white', border: '1px solid #e5e7eb', borderRadius: 8, boxShadow: '0 4px 16px rgba(0,0,0,0.10)', zIndex: 20, maxHeight: 220, overflowY: 'auto', marginTop: 4 }}>
                  {customersData.length === 0 && (
                    <div style={{ padding: '10px 14px', fontSize: 13, color: '#9ca3af' }}>Δεν βρέθηκαν πελάτες</div>
                  )}
                  {customersData.map(c => (
                    <button key={c.id} onClick={() => assignCustomer.mutate(c.id)}
                      style={{ display: 'block', width: '100%', textAlign: 'left', padding: '9px 14px', border: 'none', background: 'none', cursor: 'pointer', fontSize: 13, borderBottom: '1px solid #f3f4f6' }}
                      className="hover:bg-blue-50"
                    >
                      <span style={{ fontWeight: 600, color: '#111315' }}>{c.name}</span>
                      {c.nickname && <span style={{ color: '#9ca3af', marginLeft: 5 }}>«{c.nickname}»</span>}
                      {c.phone && <span style={{ color: '#6b7280', marginLeft: 8, fontSize: 12 }}>{c.phone}</span>}
                    </button>
                  ))}
                  <button onClick={() => { setShowCustomerDropdown(false); setCustomerSearch('') }}
                    style={{ display: 'block', width: '100%', padding: '8px 14px', fontSize: 12, color: '#9ca3af', border: 'none', background: 'none', cursor: 'pointer', borderTop: '1px solid #f0f0ef' }}>
                    Ακύρωση
                  </button>
                </div>
              </div>
            )}
          </div>
        ) : (
          <div style={{ fontSize: 13, color: '#d1d5db' }}>Χωρίς πελάτη</div>
        )}
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-gray-200">
        {[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό Συναλλαγών']].map(([key, label]) => (
          <button
            key={key}
            onClick={() => setTab(key)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${tab === key ? 'border-primary-600 text-primary-700' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
          >
            {label}
          </button>
        ))}
      </div>

      {tab === 'overview' && <>
        {/* Waiters */}
        <div className="card p-4">
          <h2 className="text-sm font-semibold text-gray-700 mb-3">Προσωπικό</h2>
          <div className="flex flex-wrap gap-2">
            {order.waiters.map(w => (
              <div key={w.waiter_id} className="flex items-center gap-2 bg-gray-100 rounded-full px-3 py-1">
                <span className="text-sm">{waiterMap[w.waiter_id] || `#${w.waiter_id}`}</span>
                {isOpen && !readOnly && (
                  <button
                    onClick={() => removeWaiter.mutate(w.waiter_id)}
                    className="text-gray-400 hover:text-red-500 text-xs leading-none"
                  >
                    ✕
                  </button>
                )}
              </div>
            ))}
            {isOpen && !readOnly && (
              <select
                className="text-sm border border-gray-300 rounded-full pl-3 pr-8 py-1 focus:outline-none focus:ring-1 focus:ring-primary-600"
                defaultValue=""
                onChange={e => { if (e.target.value) assignWaiter.mutate(Number(e.target.value)) }}
              >
                <option value="">+ Πρόσθεσε</option>
                {waiters.filter(w => !assignedIds.has(w.id)).map(w => (
                  <option key={w.id} value={w.id}>{w.nickname || w.full_name || w.username}</option>
                ))}
              </select>
            )}
          </div>
        </div>

        {/* Items */}
        <div className="card divide-y divide-gray-100">
          <div className="px-4 py-3">
            <h2 className="text-sm font-semibold text-gray-700">Αντικείμενα</h2>
          </div>
          {order.items.length === 0 && (
            <p className="px-4 py-6 text-center text-gray-400 text-sm">Κανένα αντικείμενο.</p>
          )}
          {order.items.map(item => {
            const isCancelled = item.status === 'cancelled'
            const isClosedItem = item.status === 'closed'
            const badgeStatus = isClosedItem ? 'closed_item' : item.status
            const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0)
            const isDealItem = !!item.deal_id
            const itemPriceEvents = (priceEventsMap[item.id] ?? []).filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type))
            const EVENT_COLORS_ODP = { modifier_applied: '#2563eb', waiter_discount: '#7c3aed', free_item_added: '#16a34a' }
            return (
              <div key={item.id} className={`flex items-center gap-3 px-4 py-3 ${isCancelled ? 'opacity-40 line-through' : ''} ${isClosedItem ? 'bg-amber-50/50' : ''}`}>
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-gray-800 text-sm" style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                    {item.product?.name ?? `#${item.product_id}`}
                    {item.course_id != null && (
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        width: 18, height: 18, borderRadius: '50%',
                        background: '#6366f1', color: '#fff',
                        fontSize: 10, fontWeight: 700,
                      }} title="Course">
                        {item.course_id}
                      </span>
                    )}
                    {isDealItem && <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 5px', borderRadius: 4, background: 'rgba(167,139,250,0.12)', color: '#7c3aed', border: '1px solid rgba(167,139,250,0.3)' }}>ΔΩΡΕΑΝ</span>}
                  </p>
                  {item.notes && <p className="text-xs text-gray-400">{item.notes}</p>}
                  <p className="text-xs" style={{ color: hasPriceAdj ? '#3b82f6' : '#6b7280' }}>
                    x{item.quantity} · €{effPrice(item).toFixed(2)}/τμχ
                    {hasPriceAdj && (
                      <span className="ml-1 line-through text-gray-400">€{(item.unit_price ?? 0).toFixed(2)}</span>
                    )}
                  </p>
                  {itemPriceEvents.map((ev, ei) => {
                    const evColor = EVENT_COLORS_ODP[ev.event_type] || '#8a9099'
                    const evLabel = ev.modifier_name || ev.deal_name || (ev.event_type === 'waiter_discount' ? 'Έκπτωση' : ev.event_type === 'free_item_added' ? 'Δωρεάν' : ev.event_type)
                    return (
                      <p key={ei} className="text-xs" style={{ color: evColor, display: 'flex', alignItems: 'center', gap: 3 }}>
                        <span style={{ opacity: 0.6 }}>↳</span>
                        <span>{evLabel}</span>
                        {ev.delta_amount != null && <span style={{ fontWeight: 600 }}>{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €</span>}
                      </p>
                    )
                  })}
                  {item.paid_by && (
                    <p className="text-xs text-green-600 mt-0.5">
                      Πληρώθηκε: {item.paid_by_name ?? waiterMap[item.paid_by] ?? `#${item.paid_by}`}
                      {item.paid_at ? ` · ${formatDate(item.paid_at)}` : ''}
                      {item.payment_method && (
                        <span style={{ color: (PAYMENT_METHOD_STYLES[item.payment_method] || {}).color ?? '#374151', fontWeight: 600 }}>
                          {' · '}{(PAYMENT_METHOD_STYLES[item.payment_method] || { label: item.payment_method.toUpperCase() }).label}
                        </span>
                      )}
                    </p>
                  )}
                  {isClosedItem && (
                    <p className="text-xs text-amber-700 mt-0.5 font-medium">Απλήρωτο — κλείστηκε από manager</p>
                  )}
                </div>
                <div className="flex items-center gap-2 shrink-0">
                  <span className="text-sm font-semibold w-14 text-right" style={{ color: hasPriceAdj ? '#3b82f6' : '#374151' }}>€{itemTotal(item)}</span>
                  {isOpen && !readOnly && item.status === 'active' && (
                    <>
                      <button
                        onClick={() => requestPay([item.id])}
                        className="btn btn-secondary text-xs px-2 py-1 min-h-0 h-8"
                      >
                        Πληρωμή
                      </button>
                      {order.customer_id && (
                        <button
                          onClick={() => tabItem.mutate(item.id)}
                          style={{ fontSize: 12, padding: '0 8px', height: 32, borderRadius: 6, border: '1px solid #bfdbfe', background: '#eff6ff', color: '#1d4ed8', cursor: 'pointer', fontWeight: 600, whiteSpace: 'nowrap' }}
                        >
                          📋 Καρτέλα
                        </button>
                      )}
                      <button
                        onClick={() => setConfirmAction({ type: 'cancelItem', payload: item.id })}
                        className="btn btn-danger text-xs px-2 py-1 min-h-0 h-8"
                      >
                        Ακύρωση
                      </button>
                    </>
                  )}
                  {item.status === 'tabbed' && (
                    <span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: '#eff6ff', color: '#1d4ed8', border: '1px solid #bfdbfe' }}>
                      📋 Καρτέλα
                    </span>
                  )}
                </div>
              </div>
            )
          })}
        </div>

        {/* Actions */}
        <div className="flex flex-wrap gap-3">
          {isOpen && !readOnly && activeItems.length > 0 && (
            <button
              onClick={() => requestPay(activeItems.map(i => i.id))}
              className="btn btn-primary"
            >
              Πληρωμή όλων
            </button>
          )}
          {isOpen && !readOnly && (
            <>
              <button
                onClick={() => setConfirmAction({ type: 'closeOrder' })}
                className="btn btn-secondary"
              >
                Κλείσιμο παραγγελίας
              </button>
              <button
                onClick={() => setConfirmAction({ type: 'cancelOrder' })}
                className="btn btn-danger"
              >
                Ακύρωση παραγγελίας
              </button>
            </>
          )}
          <button
            onClick={() => setShowPrintModal(true)}
            className="btn btn-secondary"
          >
            🖨 Εκτύπωση
          </button>
        </div>
      </>}

      {tab === 'pricing' && (
        <div className="card divide-y divide-gray-100">
          <PriceEventsTab orderId={orderId} />
        </div>
      )}

      {tab === 'audit' && (
        <div className="card divide-y divide-gray-100">
          <AuditTab order={order} waiterMap={waiterMap} />
        </div>
      )}

      {payPending && (
        <PaymentMethodModal
          onSelect={confirmPay}
          onCancel={() => setPayPending(null)}
          title={payPending.length === 1 ? 'Τρόπος Πληρωμής;' : `Πληρωμή ${payPending.length} αντικειμένων;`}
        />
      )}

      {confirmAction && (
        <ConfirmModal
          title={
            confirmAction.type === 'cancelItem' ? 'Ακύρωση αντικειμένου;' :
            confirmAction.type === 'cancelOrder' ? 'Ακύρωση παραγγελίας;' :
            'Κλείσιμο παραγγελίας;'
          }
          message={
            confirmAction.type === 'cancelOrder'
              ? 'Η παραγγελία θα ακυρωθεί οριστικά.'
              : undefined
          }
          confirmLabel={confirmAction.type === 'closeOrder' ? 'Κλείσιμο' : 'Ακύρωση'}
          confirmVariant={confirmAction.type === 'closeOrder' ? 'primary' : 'danger'}
          onConfirm={handleConfirm}
          onCancel={() => setConfirmAction(null)}
        />
      )}

      {showPrintModal && printers.length > 0 && (
        <PrintOrderModal
          printers={printers}
          onClose={() => setShowPrintModal(false)}
          onPrint={(printerId) => printOrder.mutate(printerId)}
        />
      )}
      {showPrintModal && printers.length === 0 && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
          <div className="bg-white rounded-2xl p-6 max-w-sm w-full mx-4 space-y-4">
            <p className="text-gray-700">Δεν βρέθηκαν ενεργοί εκτυπωτές.</p>
            <button onClick={() => setShowPrintModal(false)} className="btn btn-secondary w-full">Κλείσιμο</button>
          </div>
        </div>
      )}
    </div>
    </div>
  )
}
