import { useState } from 'react'

const _UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
function fmtQty(qty, unitType) {
  const label = _UNIT_LABELS[unitType]
  if (!label) return `×${qty}`
  if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}`
  return `${qty}${label}`
}
function fmtEUR(v) { return Number(v || 0).toFixed(2) + ' €' }

// Flatten selected_options into readable lines
function describeOptions(selected_options) {
  if (!selected_options?.length) return []
  return selected_options.map(o => {
    let s = o.name || ''
    if (o.price_delta && Math.abs(o.price_delta) > 0.001) {
      s += ` (${o.price_delta > 0 ? '+' : ''}${o.price_delta.toFixed(2)} €)`
    }
    return s
  }).filter(Boolean)
}

function CartItemSummaryRow({ item, product, onEdit }) {
  const price = (item.unit_price ?? product?.base_price ?? 0) * item.quantity
  const opts = describeOptions(item.selected_options)
  const removed = item.removed_ingredients || []

  return (
    <div style={{
      background: 'var(--bg2)', borderRadius: 14, padding: '12px 14px',
      border: '1px solid var(--border)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
            <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>{product?.name ?? `#${item.product_id}`}</span>
            <span style={{ fontSize: 13, color: 'var(--muted)', fontWeight: 500 }}>{fmtQty(item.quantity, item.unit_type)}</span>
          </div>
          {opts.length > 0 && (
            <div style={{ marginTop: 5, display: 'flex', flexWrap: 'wrap', gap: '3px 8px' }}>
              {opts.map((o, i) => (
                <span key={i} style={{ fontSize: 12, color: '#f59e0b', fontWeight: 600, background: 'rgba(245,158,11,0.08)', borderRadius: 6, padding: '1px 6px' }}>{o}</span>
              ))}
            </div>
          )}
          {removed.length > 0 && (
            <div style={{ marginTop: 4, display: 'flex', flexWrap: 'wrap', gap: '3px 8px' }}>
              {removed.map((r, i) => (
                <span key={i} style={{ fontSize: 12, color: '#ef4444', fontWeight: 600, background: 'rgba(239,68,68,0.08)', borderRadius: 6, padding: '1px 6px' }}>− {r}</span>
              ))}
            </div>
          )}
          {item.notes && (
            <div style={{ marginTop: 5, fontSize: 12, color: 'var(--muted)', fontStyle: 'italic', background: 'var(--bg3)', borderRadius: 7, padding: '4px 8px' }}>
              "{item.notes}"
            </div>
          )}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
          <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(price)}</span>
          {onEdit && (
            <button
              onClick={onEdit}
              style={{ background: 'var(--bg3)', border: '1px solid var(--border)', borderRadius: 7, padding: '3px 10px', fontSize: 12, color: 'var(--muted)', cursor: 'pointer', fontWeight: 600 }}
            >
              Επεξεργασία
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

export default function OrderSummaryModal({ cart, products, orderNote, setOrderNote, onSend, onClose, sending }) {
  const [noteEditing, setNoteEditing] = useState(false)

  const total = cart.reduce((s, item) => s + (item.unit_price ?? 0) * item.quantity, 0)

  function getProduct(id) { return products.find(p => p.id === id) }

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 200 }}
      />

      {/* Sheet */}
      <div style={{
        position: 'fixed', inset: 0,
        background: 'var(--bg)',
        zIndex: 201,
        display: 'flex', flexDirection: 'column',
        animation: 'summarySlideUp 260ms cubic-bezier(0.32,0.72,0,1)',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '14px 16px', borderBottom: '1px solid var(--border)', flexShrink: 0,
        }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--text)' }}>Επισκόπηση Παραγγελίας</div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>{cart.length} {cart.length === 1 ? 'προϊόν' : 'προϊόντα'} · {fmtEUR(total)}</div>
          </div>
          <button
            onClick={onClose}
            style={{ background: 'var(--bg3)', border: 'none', borderRadius: '50%', width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--text)' }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Item list */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 12px 0' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {cart.map(item => (
              <CartItemSummaryRow
                key={item._key}
                item={item}
                product={getProduct(item.product_id)}
              />
            ))}
          </div>

          {/* Order note section */}
          <div style={{ marginTop: 16, marginBottom: 8 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.7, marginBottom: 8 }}>
              Σημείωση Παραγγελίας
            </div>
            {noteEditing ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <textarea
                  autoFocus
                  value={orderNote}
                  onChange={e => setOrderNote(e.target.value)}
                  placeholder="Σημείωση για ολόκληρη την παραγγελία…"
                  rows={3}
                  style={{
                    width: '100%', resize: 'none', padding: '10px 12px',
                    background: 'rgba(245,158,11,0.07)', border: '1.5px solid rgba(245,158,11,0.35)',
                    borderRadius: 10, fontSize: 14, color: 'var(--text)', lineHeight: 1.5,
                    outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
                  }}
                />
                <button
                  onClick={() => setNoteEditing(false)}
                  style={{ alignSelf: 'flex-end', background: 'none', border: 'none', fontSize: 12, fontWeight: 700, color: 'var(--accent)', cursor: 'pointer' }}
                >
                  Αποθήκευση
                </button>
              </div>
            ) : orderNote ? (
              <div
                onClick={() => setNoteEditing(true)}
                style={{ cursor: 'pointer', padding: '10px 13px', background: 'rgba(245,158,11,0.09)', border: '1.5px solid rgba(245,158,11,0.3)', borderRadius: 10, fontSize: 14, color: 'var(--text)', lineHeight: 1.5, whiteSpace: 'pre-wrap', position: 'relative' }}
              >
                {orderNote}
                <span style={{ position: 'absolute', top: 8, right: 10, fontSize: 12, color: '#f59e0b', fontWeight: 700 }}>✎</span>
              </div>
            ) : (
              <button
                onClick={() => setNoteEditing(true)}
                style={{
                  width: '100%', padding: '10px 13px',
                  background: 'var(--bg2)', border: '1.5px dashed var(--border)',
                  borderRadius: 10, fontSize: 13, color: 'var(--muted)',
                  cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 7,
                }}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Προσθήκη σημείωσης παραγγελίας
              </button>
            )}
          </div>

          {/* Total */}
          <div style={{ marginTop: 12, marginBottom: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 4px', borderTop: '1px solid var(--border)' }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.6 }}>Σύνολο</span>
            <span style={{ fontSize: 20, fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(total)}</span>
          </div>
        </div>

        {/* Footer — Send button */}
        <div style={{ padding: '12px 12px 28px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
          <button
            className="btn btn--primary btn--lg"
            style={{ width: '100%' }}
            onClick={onSend}
            disabled={sending}
          >
            {sending ? 'Αποστολή…' : `ΑΠΟΣΤΟΛΗ (${cart.length})`}
          </button>
        </div>

        <style>{`
          @keyframes summarySlideUp {
            from { transform: translateY(100%); opacity: 0; }
            to   { transform: translateY(0);    opacity: 1; }
          }
        `}</style>
      </div>
    </>
  )
}
