import { useRef } from 'react'

function fmtPrice(v) {
  return Number(v).toFixed(2) + ' €'
}

function ItemRow({ item, selectable, selected, onToggle, onLongPress, isLast }) {
  const isPaid = item.status === 'paid'
  const isCancelled = item.status === 'cancelled'
  const isStacked = item.quantity > 1

  let opts = []
  try { opts = item.selected_options ? JSON.parse(item.selected_options) : [] } catch {}
  let removed = []
  try { removed = item.removed_ingredients ? JSON.parse(item.removed_ingredients) : [] } catch {}

  // Long-press detection — only fires if the finger hasn't moved (avoids triggering during scroll)
  const pressTimer = useRef(null)
  const didLongPress = useRef(false)
  const touchStartPos = useRef({ x: 0, y: 0 })

  function handleTouchStart(e) {
    if (!selectable || isPaid || isCancelled || !isStacked || !onLongPress) return
    didLongPress.current = false
    touchStartPos.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }
    pressTimer.current = setTimeout(() => {
      didLongPress.current = true
      onLongPress(item)
    }, 500)
  }

  function handleTouchMove(e) {
    const dx = Math.abs(e.touches[0].clientX - touchStartPos.current.x)
    const dy = Math.abs(e.touches[0].clientY - touchStartPos.current.y)
    if (dx > 8 || dy > 8) clearTimeout(pressTimer.current)
  }

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

  function handleClick() {
    if (didLongPress.current) { didLongPress.current = false; return }
    if (selectable && !isPaid && !isCancelled) onToggle(item.id)
  }

  return (
    <div
      className={`order-item ${isPaid ? 'order-item--paid' : ''} ${isCancelled ? 'order-item--cancelled' : ''} ${selectable && selected ? 'order-item--selected' : ''} ${isLast ? 'order-item--last' : ''}`}
      onClick={handleClick}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
      onTouchCancel={handleTouchEnd}
      style={{ cursor: selectable && !isPaid && !isCancelled ? 'pointer' : 'default', userSelect: 'none' }}
    >
      <div className="order-item__row">
        {selectable && !isPaid && !isCancelled && (
          <span style={{ marginRight: 8, color: selected ? '#f59e0b' : '#475569' }}>
            {selected ? '☑' : '☐'}
          </span>
        )}
        <span className="order-item__name">{item.product?.name || `#${item.product_id}`}</span>
        <span className="order-item__qty">×{item.quantity}</span>
        <span className="order-item__price">{fmtPrice(item.unit_price * item.quantity)}</span>
        {isPaid && <span className="badge badge--paid">Paid</span>}
        {isCancelled && <span className="badge badge--cancelled">Cancelled</span>}
        {!isPaid && !isCancelled && !item.printed && (
          <span className="badge badge--draft" title="Δεν εκτυπώθηκε ακόμα">⏳</span>
        )}
      </div>
      {opts.map((o, i) => <div key={i} className="order-item__modifier">+ {o.name} {o.price_delta > 0 ? `(+${fmtPrice(o.price_delta)})` : ''}</div>)}
      {removed.map((r, i) => <div key={i} className="order-item__modifier">- {r}</div>)}
      {item.notes && <div className="order-item__modifier">📝 {item.notes}</div>}
    </div>
  )
}

export default function OrderSummary({ order, selectable = false, selectedIds = [], onToggle, onLongPressItem }) {
  const activeItems = order.items?.filter(i => i.status !== 'cancelled') || []
  const total = activeItems
    .filter(i => i.status !== 'cancelled')
    .reduce((s, i) => s + i.unit_price * i.quantity, 0)
  const paidTotal = activeItems
    .filter(i => i.status === 'paid')
    .reduce((s, i) => s + i.unit_price * i.quantity, 0)

  return (
    <div className="order-summary">
      {activeItems.length === 0 && <p style={{ color: '#64748b', textAlign: 'center' }}>Δεν υπάρχουν αντικείμενα</p>}
      {activeItems.map((item, idx) => (
        <ItemRow
          key={item.id}
          item={item}
          selectable={selectable}
          selected={selectedIds.includes(item.id)}
          onToggle={onToggle}
          onLongPress={onLongPressItem}
          isLast={idx === activeItems.length - 1}
        />
      ))}
      <div className="order-summary__total">
        <span>Σύνολο</span>
        <span>{fmtPrice(total)}</span>
      </div>
      {paidTotal > 0 && paidTotal < total && (
        <div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: 8, fontSize: 13, color: '#64748b' }}>
          <span>Πληρωμένο</span>
          <span style={{ color: '#22c55e' }}>{fmtPrice(paidTotal)}</span>
        </div>
      )}
      {paidTotal > 0 && paidTotal < total && (
        <div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: 8, fontSize: 13, color: '#94a3b8' }}>
          <span>Εκκρεμεί</span>
          <span style={{ color: '#f59e0b', fontWeight: 700 }}>{fmtPrice(total - paidTotal)}</span>
        </div>
      )}
    </div>
  )
}
