import { useState, useEffect, useCallback, useRef } from 'react'
import { useSearchParams } from 'react-router-dom'
import AppShell from '../components/AppShell'
import client from '../api/client'

// ── helpers ───────────────────────────────────────────────────────────────────

function fmtTime(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}

function fmtDateTime(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleString('el-GR', {
    day: '2-digit', month: '2-digit',
    hour: '2-digit', minute: '2-digit',
  })
}

function fmtPrice(n) {
  return '€' + parseFloat(n || 0).toFixed(2)
}

// ── icons ─────────────────────────────────────────────────────────────────────

function PrintOkIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
      <path d="M6 9V2h12v7" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="#22c55e" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <rect x="6" y="14" width="12" height="8" rx="1" stroke="#22c55e" strokeWidth="2"/>
    </svg>
  )
}

function PrintFailIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
      <path d="M6 9V2h12v7" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <rect x="6" y="14" width="12" height="8" rx="1" stroke="#ef4444" strokeWidth="2"/>
      <path d="M10 17l4 4M14 17l-4 4" stroke="#ef4444" strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  )
}

// Receipt SVG from ASSETS/ICONS/receipt.svg, coloured by fiscal status
function FiscalStatusIcon({ status }) {
  if (!status) return null
  const color = status === 'success' ? '#22c55e' : status === 'pending' ? '#f59e0b' : '#ef4444'
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M17 13H21V19C21 20.1046 20.1046 21 19 21M17 13V19C17 20.1046 17.8954 21 19 21M17 13V5.75707C17 4.85168 17 4.39898 16.8098 4.13646C16.6439 3.90746 16.3888 3.75941 16.1076 3.72897C15.7853 3.69408 15.3923 3.91868 14.6062 4.36788L14.2938 4.54637C14.0045 4.7117 13.8598 4.79438 13.7062 4.82675C13.5702 4.85539 13.4298 4.85539 13.2938 4.82675C13.1402 4.79438 12.9955 4.7117 12.7062 4.54637L10.7938 3.45359C10.5045 3.28826 10.3598 3.20559 10.2062 3.17322C10.0702 3.14457 9.92978 3.14457 9.79383 3.17322C9.64019 3.20559 9.49552 3.28826 9.20618 3.4536L7.29382 4.54637C7.00448 4.71171 6.85981 4.79438 6.70617 4.82675C6.57022 4.85539 6.42978 4.85539 6.29383 4.82675C6.14019 4.79438 5.99552 4.71171 5.70618 4.54637L5.39382 4.36788C4.60772 3.91868 4.21467 3.69408 3.89237 3.72897C3.61123 3.75941 3.35611 3.90746 3.1902 4.13646C3 4.39898 3 4.85168 3 5.75707V16.2C3 17.8801 3 18.7202 3.32698 19.362C3.6146 19.9264 4.07354 20.3854 4.63803 20.673C5.27976 21 6.11984 21 7.8 21H19M12 10.5C11.5 10.376 10.6851 10.3714 10 10.376C9.77091 10.3775 9.90941 10.3678 9.6 10.376C8.79258 10.4012 8.00165 10.7368 8 11.6875C7.99825 12.7003 9 13 10 13C11 13 12 13.2312 12 14.3125C12 15.1251 11.1925 15.4812 10.1861 15.5991C9.3861 15.5991 9 15.625 8 15.5M10 16V17M10 8.99998V9.99998" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  )
}

function CompactIcon({ active }) {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <rect x="3" y="5" width="18" height="3" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
      <rect x="3" y="11" width="18" height="3" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
      <rect x="3" y="17" width="18" height="3" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
    </svg>
  )
}

function DetailedIcon({ active }) {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
      <rect x="3" y="3" width="18" height="7" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
      <rect x="3" y="13" width="18" height="7" rx="1.5" fill={active ? 'var(--accent)' : 'var(--muted)'}/>
    </svg>
  )
}

function FilterIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M3 6h18M7 12h10M11 18h2" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
    </svg>
  )
}

// ── action sheet — long-press on detailed cards ───────────────────────────────

function PrintActionSheet({ order, onRetry, onCancel, onClose, busy }) {
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(0,0,0,0.55)',
        display: 'flex', alignItems: 'flex-end',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', background: 'var(--bg)',
          borderRadius: '20px 20px 0 0',
          padding: '12px 16px 32px',
          boxShadow: '0 -4px 20px rgba(0,0,0,0.4)',
        }}
      >
        <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 16px' }} />
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 4 }}>
          Πρόβλημα Εκτύπωσης
        </div>
        <div style={{ fontSize: 13, color: 'var(--muted)', marginBottom: 20 }}>
          Παραγγελία #{order.id} · {order.table_name} · {fmtTime(order.opened_at)}
          {order.print_retry_count > 0 && (
            <span style={{ marginLeft: 8, color: '#f59e0b' }}>
              {order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'}
            </span>
          )}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button
            onClick={onRetry}
            disabled={busy}
            style={{
              padding: '14px', borderRadius: 12, border: 'none',
              background: 'var(--accent)', color: '#fff',
              fontSize: 15, fontWeight: 700, cursor: busy ? 'default' : 'pointer',
              opacity: busy ? 0.6 : 1,
            }}
          >
            {busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'}
          </button>
          <button
            onClick={onCancel}
            disabled={busy}
            style={{
              padding: '14px', borderRadius: 12,
              border: '1px solid #fee2e2', background: '#fff5f5',
              fontSize: 15, fontWeight: 600, color: '#dc2626',
              cursor: busy ? 'default' : 'pointer',
              opacity: busy ? 0.6 : 1,
            }}
          >
            Ακύρωση Εκτύπωσης
          </button>
          <button
            onClick={onClose}
            style={{
              padding: '14px', borderRadius: 12,
              border: '1px solid var(--border)', background: 'var(--bg2)',
              fontSize: 15, color: 'var(--muted)', cursor: 'pointer',
            }}
          >
            Κλείσιμο
          </button>
        </div>
      </div>
    </div>
  )
}

// ── filter sheet ──────────────────────────────────────────────────────────────

function FilterSheet({ filter, dateFrom, dateTo, onApply, onClose }) {
  const [localFilter, setLocalFilter] = useState(filter)
  const [localFrom, setLocalFrom] = useState(dateFrom)
  const [localTo, setLocalTo] = useState(dateTo)

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(0,0,0,0.55)',
        display: 'flex', alignItems: 'flex-end',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', background: 'var(--bg)',
          borderRadius: '20px 20px 0 0',
          padding: '12px 16px 40px',
          boxShadow: '0 -4px 20px rgba(0,0,0,0.4)',
        }}
      >
        <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--border)', margin: '0 auto 20px' }} />
        <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>Φίλτρα</div>

        {/* Status filter */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Κατάσταση
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { value: 'all', label: 'Όλες' },
              { value: 'success', label: 'Επιτυχής' },
              { value: 'failed', label: 'Αποτυχημένη' },
            ].map(opt => (
              <button
                key={opt.value}
                onClick={() => setLocalFilter(opt.value)}
                style={{
                  flex: 1, padding: '10px 4px', borderRadius: 10,
                  border: `1px solid ${localFilter === opt.value ? 'var(--accent)' : 'var(--border)'}`,
                  background: localFilter === opt.value ? 'rgba(var(--accent-rgb,59,130,246),0.12)' : 'var(--bg2)',
                  color: localFilter === opt.value ? 'var(--accent)' : 'var(--text)',
                  fontSize: 13, fontWeight: localFilter === opt.value ? 700 : 500,
                  cursor: 'pointer',
                }}
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>

        {/* Date range */}
        <div style={{ marginBottom: 24 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Εύρος ημερομηνίας/ώρας
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>Από</span>
              <input
                type="datetime-local"
                value={localFrom}
                onChange={e => setLocalFrom(e.target.value)}
                style={{
                  flex: 1, height: 38, borderRadius: 10,
                  border: '1px solid var(--border)', background: 'var(--bg2)',
                  padding: '0 10px', fontSize: 13, color: 'var(--text)',
                  fontFamily: 'inherit', outline: 'none',
                }}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ fontSize: 12, color: 'var(--muted)', width: 28 }}>Έως</span>
              <input
                type="datetime-local"
                value={localTo}
                onChange={e => setLocalTo(e.target.value)}
                style={{
                  flex: 1, height: 38, borderRadius: 10,
                  border: '1px solid var(--border)', background: 'var(--bg2)',
                  padding: '0 10px', fontSize: 13, color: 'var(--text)',
                  fontFamily: 'inherit', outline: 'none',
                }}
              />
            </div>
            {(localFrom || localTo) && (
              <button
                onClick={() => { setLocalFrom(''); setLocalTo('') }}
                style={{
                  alignSelf: 'flex-start', fontSize: 12, color: 'var(--muted)',
                  background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0',
                }}
              >
                Καθαρισμός ημερομηνίας
              </button>
            )}
          </div>
        </div>

        <button
          onClick={() => onApply(localFilter, localFrom, localTo)}
          style={{
            width: '100%', padding: '14px', borderRadius: 12, border: 'none',
            background: 'var(--accent)', color: '#fff',
            fontSize: 15, fontWeight: 700, cursor: 'pointer',
          }}
        >
          Εφαρμογή
        </button>
      </div>
    </div>
  )
}

// ── compact card (click = expand inline, expanded shows action buttons) ────────

function CompactCard({ order, expanded, onToggle, onRetry, onCancel, busy }) {
  const isPending = order.print_status === 'pending'

  return (
    <div
      style={{
        background: 'var(--bg2)',
        border: `1px solid ${isPending ? 'rgba(239,68,68,0.4)' : 'var(--border)'}`,
        borderRadius: 12,
        cursor: 'pointer',
        transition: 'border-color 0.15s',
      }}
      onClick={() => onToggle(order.id)}
    >
      {/* Always-visible summary row */}
      <div style={{ padding: '10px 14px' }}>
        {/* 3-column grid: table name | centered order# | print icon */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 4 }}>
          <span style={{
            fontSize: 14, fontWeight: 700, color: 'var(--text)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {order.table_name || '—'}
          </span>
          <span style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>
            #{order.id}
          </span>
          <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 4 }}>
            <FiscalStatusIcon status={order.fiscal_status} />
            {isPending ? <PrintFailIcon /> : <PrintOkIcon />}
          </span>
        </div>
        {/* Row 2: item count | total */}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 5 }}>
          <span style={{ fontSize: 12, color: 'var(--muted)' }}>
            {order.items.length} αντ.
          </span>
          <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)' }}>
            {fmtPrice(order.total)}
          </span>
        </div>
      </div>

      {/* Expanded section — items + action buttons for pending */}
      {expanded && (
        <>
          <div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
          <div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 3 }}>
            {order.items.map(item => (
              <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                <span style={{ color: 'var(--text)', flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {item.product_name}
                </span>
                <span style={{ color: 'var(--muted)', marginLeft: 8, flexShrink: 0 }}>
                  ×{item.quantity % 1 === 0 ? item.quantity : item.quantity.toFixed(2)}
                </span>
              </div>
            ))}
          </div>
          {/* Total + fiscal info */}
          <div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />
          <div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--muted)' }}>Σύνολο</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                {isPending && order.print_retry_count > 0 && (
                  <span style={{ fontSize: 11, color: '#f59e0b' }}>
                    {order.print_retry_count} επανάληψ{order.print_retry_count === 1 ? 'η' : 'εις'}
                  </span>
                )}
                <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{fmtPrice(order.total)}</span>
              </div>
            </div>
            {order.fiscal_status && (
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                <span style={{ color: 'var(--muted)' }}>Φορολογική εκτύπωση</span>
                <span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}>
                  {order.fiscal_status === 'success' ? 'Επιτυχής' : order.fiscal_status === 'pending' ? 'Εκκρεμεί…' : 'Αποτυχία'}
                </span>
              </div>
            )}
          </div>
          {isPending && (
          <>
          <div style={{ borderTop: '1px solid var(--border)', margin: '0 14px' }} />
          <div style={{ padding: '10px 14px', display: 'flex', gap: 8 }} onClick={e => e.stopPropagation()}>
            <button
              onClick={() => onRetry(order)}
              disabled={busy}
              style={{
                flex: 1, padding: '10px 8px', borderRadius: 10, border: 'none',
                background: 'var(--accent)', color: '#fff',
                fontSize: 13, fontWeight: 700, cursor: busy ? 'default' : 'pointer',
                opacity: busy ? 0.6 : 1,
              }}
            >
              {busy ? 'Αποστολή…' : 'Εκτύπωση Τώρα'}
            </button>
            <button
              onClick={() => onCancel(order)}
              disabled={busy}
              style={{
                flex: 1, padding: '10px 8px', borderRadius: 10,
                border: '1px solid #fee2e2', background: '#fff5f5',
                fontSize: 13, fontWeight: 600, color: '#dc2626',
                cursor: busy ? 'default' : 'pointer',
                opacity: busy ? 0.6 : 1,
              }}
            >
              Ακύρωση
            </button>
          </div>
          </>
          )}
        </>
      )}
    </div>
  )
}

// ── detailed card (long-press = action sheet) ─────────────────────────────────

function DetailedCard({ order, onLongPress }) {
  const isPending = order.print_status === 'pending'
  const pressTimer = useRef(null)

  function startPress() {
    if (!isPending) return
    pressTimer.current = setTimeout(() => onLongPress(order), 600)
  }

  function cancelPress() {
    clearTimeout(pressTimer.current)
  }

  return (
    <div
      onPointerDown={startPress}
      onPointerUp={cancelPress}
      onPointerLeave={cancelPress}
      style={{
        background: 'var(--bg2)',
        border: `1px solid ${isPending ? 'rgba(239,68,68,0.4)' : 'var(--border)'}`,
        borderRadius: 14,
        cursor: isPending ? 'pointer' : 'default',
        userSelect: 'none',
        WebkitUserSelect: 'none',
      }}
    >
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '11px 14px',
        background: isPending ? 'rgba(239,68,68,0.06)' : 'var(--bg3)',
        borderBottom: '1px solid var(--border)',
        borderRadius: '14px 14px 0 0',
      }}>
        <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', flex: 1 }}>
          {order.table_name || '—'}
        </span>
        <span style={{ fontSize: 12, color: 'var(--muted)' }}>#{order.id}</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <FiscalStatusIcon status={order.fiscal_status} />
          {isPending ? <PrintFailIcon /> : <PrintOkIcon />}
        </span>
      </div>

      {/* Meta rows */}
      <div style={{ padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 5 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
          <span style={{ color: 'var(--muted)' }}>Παραγγέλθηκε</span>
          <span style={{ color: 'var(--text)', fontWeight: 500 }}>{fmtDateTime(order.opened_at)}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
          <span style={{ color: 'var(--muted)' }}>Εκτύπωση</span>
          <span style={{ fontWeight: 600, color: isPending ? '#ef4444' : '#22c55e' }}>
            {isPending
              ? `Εκκρεμεί (${order.print_retry_count} επαν.)`
              : `OK ${fmtTime(order.print_attempted_at)}`}
          </span>
        </div>
        {order.fiscal_status && (
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
            <span style={{ color: 'var(--muted)' }}>Φορολογική εκτύπωση</span>
            <span style={{ fontWeight: 600, color: order.fiscal_status === 'success' ? '#22c55e' : order.fiscal_status === 'pending' ? '#f59e0b' : '#ef4444' }}>
              {order.fiscal_status === 'success' ? 'Επιτυχής' : order.fiscal_status === 'pending' ? 'Εκκρεμεί…' : 'Αποτυχία'}
            </span>
          </div>
        )}
      </div>

      {/* Divider */}
      <div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />

      {/* Items — no fixed height, auto-sizes to content */}
      <div style={{ padding: '8px 14px', display: 'flex', flexDirection: 'column', gap: 4 }}>
        {order.items.map(item => (
          <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
            <span style={{ color: 'var(--text)', flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {item.product_name}
            </span>
            <span style={{ color: 'var(--muted)', marginLeft: 8, flexShrink: 0 }}>
              ×{item.quantity % 1 === 0 ? item.quantity : item.quantity.toFixed(2)}
            </span>
          </div>
        ))}
      </div>

      {/* Divider */}
      <div style={{ borderTop: '1px dashed var(--border)', margin: '0 14px' }} />

      {/* Total */}
      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 14px', fontSize: 14 }}>
        <span style={{ color: 'var(--muted)', fontWeight: 600 }}>Σύνολο</span>
        <span style={{ color: 'var(--text)', fontWeight: 700 }}>{fmtPrice(order.total)}</span>
      </div>

      {isPending && (
        <div style={{ padding: '0 14px 10px', textAlign: 'center' }}>
          <span style={{ fontSize: 11, color: 'var(--muted)' }}>Κρατήστε πατημένο για επιλογές</span>
        </div>
      )}
    </div>
  )
}

// ── main page ─────────────────────────────────────────────────────────────────

export default function OrderLogPage() {
  const [searchParams] = useSearchParams()
  const initialFilter = searchParams.get('filter') === 'failed' ? 'failed' : 'all'

  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(true)
  const [view, setView] = useState('compact')
  const [search, setSearch] = useState('')
  const [filter, setFilter] = useState(initialFilter)
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [showFilter, setShowFilter] = useState(false)
  const [expandedId, setExpandedId] = useState(null)
  const [actionOrder, setActionOrder] = useState(null)
  const [actionBusy, setActionBusy] = useState(false)

  const load = useCallback(async () => {
    try {
      const res = await client.get('/api/orders/shift-log')
      setOrders(res.data?.orders ?? [])
    } catch {
      // keep stale data
    } finally {
      setLoading(false)
    }
  }, [])

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

  useEffect(() => {
    const id = setInterval(load, 10000)
    return () => clearInterval(id)
  }, [load])

  function toggleExpand(id) {
    setExpandedId(prev => prev === id ? null : id)
  }

  const q = search.trim().toLowerCase()
  let filtered = q
    ? orders.filter(o =>
        (o.table_name || '').toLowerCase().includes(q) ||
        String(o.id).includes(q) ||
        o.items.some(i => i.product_name.toLowerCase().includes(q))
      )
    : [...orders]

  if (filter === 'failed') {
    filtered = filtered.filter(o => o.print_status === 'pending')
  } else if (filter === 'success') {
    filtered = filtered.filter(o => o.print_status !== 'pending')
  }

  if (dateFrom) {
    const from = new Date(dateFrom)
    filtered = filtered.filter(o => new Date(o.opened_at) >= from)
  }
  if (dateTo) {
    const to = new Date(dateTo)
    filtered = filtered.filter(o => new Date(o.opened_at) <= to)
  }

  async function handleRetry(order) {
    setActionBusy(true)
    try {
      await client.post(`/api/orders/${order.id}/retry-print`)
      await load()
      setActionOrder(null)
      setExpandedId(null)
    } catch {
      // stay open so user can try again
    } finally {
      setActionBusy(false)
    }
  }

  async function handleCancelJobs(order) {
    setActionBusy(true)
    try {
      const pendingJobs = order.print_jobs.filter(j => j.status === 'pending')
      for (const job of pendingJobs) {
        await client.post(`/api/orders/${order.id}/print-jobs/${job.id}/cancel`)
      }
      await load()
      setActionOrder(null)
      setExpandedId(null)
    } catch {
      // stay open
    } finally {
      setActionBusy(false)
    }
  }

  const pendingCount = orders.filter(o => o.print_status === 'pending').length
  const hasActiveFilters = filter !== 'all' || !!dateFrom || !!dateTo

  return (
    <AppShell title="Αρχ. Παραγγ.">
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>

        {/* Toolbar */}
        <div style={{
          display: 'flex', gap: 8, alignItems: 'center',
          padding: '10px 14px',
          borderBottom: '1px solid var(--border)',
          flexShrink: 0,
        }}>
          <input
            type="search"
            placeholder="Τραπέζι, #παραγγελία, αντικείμενο…"
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{
              flex: 1, height: 38, borderRadius: 10,
              border: '1px solid var(--border)', background: 'var(--bg2)',
              padding: '0 12px', fontSize: 14, color: 'var(--text)',
              fontFamily: 'inherit', outline: 'none',
            }}
          />
          <button
            onClick={() => setView(v => v === 'compact' ? 'detailed' : 'compact')}
            style={{
              width: 38, height: 38, borderRadius: 10,
              border: `1px solid ${view === 'detailed' ? 'var(--accent)' : 'var(--border)'}`,
              background: view === 'detailed' ? 'var(--accent)18' : 'var(--bg2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer',
            }}
            title={view === 'compact' ? 'Λεπτομερής προβολή' : 'Συμπαγής προβολή'}
          >
            {view === 'compact' ? <DetailedIcon active={false} /> : <CompactIcon active={false} />}
          </button>
        </div>

        {/* Pending banner */}
        {pendingCount > 0 && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '8px 14px',
            background: 'rgba(239,68,68,0.08)',
            borderBottom: '1px solid rgba(239,68,68,0.2)',
            flexShrink: 0,
          }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="10" stroke="#ef4444" strokeWidth="2"/>
              <path d="M12 8v4M12 16h.01" stroke="#ef4444" strokeWidth="2" strokeLinecap="round"/>
            </svg>
            <span style={{ fontSize: 13, color: '#ef4444', fontWeight: 600 }}>
              {pendingCount} παραγγελί{pendingCount !== 1 ? 'ες' : 'α'} με πρόβλημα εκτύπωσης
            </span>
          </div>
        )}

        {/* Active filter chips */}
        {hasActiveFilters && (
          <div style={{
            display: 'flex', gap: 6, alignItems: 'center',
            padding: '6px 14px',
            borderBottom: '1px solid var(--border)',
            flexShrink: 0, flexWrap: 'wrap',
          }}>
            {filter !== 'all' && (
              <span style={{
                fontSize: 12, padding: '3px 10px', borderRadius: 999,
                background: filter === 'failed' ? 'rgba(239,68,68,0.12)' : 'rgba(34,197,94,0.12)',
                color: filter === 'failed' ? '#ef4444' : '#22c55e',
                fontWeight: 600,
              }}>
                {filter === 'failed' ? 'Αποτυχημένη εκτύπωση' : 'Επιτυχής εκτύπωση'}
              </span>
            )}
            {dateFrom && (
              <span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}>
                Από {new Date(dateFrom).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
              </span>
            )}
            {dateTo && (
              <span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 999, background: 'var(--bg3)', color: 'var(--muted)' }}>
                Έως {new Date(dateTo).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
              </span>
            )}
            <button
              onClick={() => { setFilter('all'); setDateFrom(''); setDateTo('') }}
              style={{ fontSize: 12, color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer', padding: '3px 6px' }}
            >
              ✕ Καθαρισμός
            </button>
          </div>
        )}

        {/* List */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px 80px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {loading && (
            <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>Φόρτωση…</p>
          )}
          {!loading && filtered.length === 0 && (
            <p style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 14 }}>
              {search || hasActiveFilters ? 'Δεν βρέθηκαν παραγγελίες' : 'Δεν υπάρχουν παραγγελίες σε αυτή τη βάρδια'}
            </p>
          )}
          {filtered.map(order =>
            view === 'compact'
              ? (
                <CompactCard
                  key={order.id}
                  order={order}
                  expanded={expandedId === order.id}
                  onToggle={toggleExpand}
                  onRetry={handleRetry}
                  onCancel={handleCancelJobs}
                  busy={actionBusy}
                />
              )
              : (
                <DetailedCard
                  key={order.id}
                  order={order}
                  onLongPress={setActionOrder}
                />
              )
          )}
        </div>

        {/* Floating filter button */}
        <button
          onClick={() => setShowFilter(true)}
          style={{
            position: 'absolute', bottom: 20, right: 20,
            width: 52, height: 52, borderRadius: '50%',
            border: 'none', cursor: 'pointer',
            background: hasActiveFilters ? 'var(--accent)' : 'var(--bg3)',
            color: hasActiveFilters ? '#fff' : 'var(--text)',
            boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: 10,
          }}
          title="Φίλτρα"
        >
          <FilterIcon />
          {hasActiveFilters && (
            <span style={{
              position: 'absolute', top: -2, right: -2,
              width: 14, height: 14, borderRadius: '50%',
              background: '#ef4444',
              border: '2px solid var(--bg)',
            }} />
          )}
        </button>
      </div>

      {/* Action sheet — long-press on detailed cards */}
      {actionOrder && (
        <PrintActionSheet
          order={actionOrder}
          busy={actionBusy}
          onRetry={() => handleRetry(actionOrder)}
          onCancel={() => handleCancelJobs(actionOrder)}
          onClose={() => setActionOrder(null)}
        />
      )}

      {/* Filter sheet */}
      {showFilter && (
        <FilterSheet
          filter={filter}
          dateFrom={dateFrom}
          dateTo={dateTo}
          onApply={(f, from, to) => {
            setFilter(f)
            setDateFrom(from)
            setDateTo(to)
            setShowFilter(false)
          }}
          onClose={() => setShowFilter(false)}
        />
      )}
    </AppShell>
  )
}
