import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { X } from 'lucide-react'
import { fmtEUR, fmtDateTime } from './reportDesignTokens'
import client from '../../../api/client'

// ── Status badge ────────────────────────────────────────────────────────────
const STATUS_META = {
  active:          { label: 'Ενεργό',               bg: '#eff6ff', text: '#1d4ed8' },
  paid:            { label: 'Πληρωμένο',             bg: '#f0fdf4', text: '#15803d' },
  cancelled:       { label: 'Ακυρωμένο',             bg: '#fef2f2', text: '#b91c1c' },
  closed:          { label: 'Κλειστό (απλήρωτο)',    bg: '#fffbeb', text: '#b45309' },
  open:            { label: 'Ανοιχτή',               bg: '#eff6ff', text: '#1d4ed8' },
  partially_paid:  { label: 'Μερική πλ.',            bg: '#fffbeb', text: '#b45309' },
}
function StatusPill({ status }) {
  const m = STATUS_META[status] || { label: status, bg: '#f9fafb', text: '#374151' }
  return (
    <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 20, background: m.bg, color: m.text }}>
      {m.label}
    </span>
  )
}

// ── Payment method chip ─────────────────────────────────────────────────────
const PAY_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 <span style={{ color: '#b8bdc4', fontSize: 12 }}>—</span>
  const s = PAY_METHOD_STYLES[method] || { label: method.toUpperCase(), color: '#374151', bg: '#f3f4f6', border: '#d1d5db' }
  return (
    <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 6, background: s.bg, color: s.color, border: `1px solid ${s.border}`, letterSpacing: 0.3, whiteSpace: 'nowrap' }}>
      {s.label}
    </span>
  )
}

// ── Audit event labels ──────────────────────────────────────────────────────
const EVENT_LABELS = {
  ORDER_OPENED:    { label: 'Άνοιγμα',           bg: '#eff6ff',  text: '#1d4ed8' },
  ITEMS_ADDED:     { label: 'Προσθήκη',           bg: '#eff6ff',  text: '#1d4ed8' },
  PAYMENT:         { label: 'Πληρωμή',            bg: '#f0fdf4',  text: '#15803d' },
  PAYMENT_OFFLINE: { label: 'Πληρωμή (Offline)',  bg: '#fffbeb',  text: '#b45309' },
  ORDER_CLOSED:    { label: 'Κλείσιμο',           bg: '#f9fafb',  text: '#374151' },
  ORDER_CANCELLED: { label: 'Ακύρωση',            bg: '#fef2f2',  text: '#b91c1c' },
  ITEM_CANCELLED:  { label: 'Ακύρωση αντ.',       bg: '#fef2f2',  text: '#b91c1c' },
  PAYMENT_REVERTED:{ label: 'Αναίρεση Πληρωμής', bg: '#fffbeb',  text: '#b45309' },
}

function AuditTimeline({ logs, itemsById }) {
  if (!logs || logs.length === 0) {
    return <p style={{ color: '#b8bdc4', fontSize: 13, textAlign: 'center', padding: '16px 0' }}>Δεν υπάρχουν εγγραφές</p>
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      {logs.map(log => {
        const meta = EVENT_LABELS[log.event_type] || { label: log.event_type, bg: '#f9fafb', text: '#374151' }
        const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true
        const displayTime = log.offline_at ? fmtDateTime(log.offline_at) : fmtDateTime(log.created_at)

        let itemNames = []
        if (log.item_ids && itemsById) {
          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} style={{
            display: 'flex', alignItems: 'flex-start', gap: 10, padding: '8px 0',
            borderBottom: '1px solid #f4f4f2',
            background: isDuplicate ? '#fef2f2' : 'transparent',
          }}>
            <div style={{ flexShrink: 0, paddingTop: 2 }}>
              <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 10, background: isDuplicate ? '#fecaca' : meta.bg, color: isDuplicate ? '#b91c1c' : meta.text }}>
                {meta.label}
              </span>
              {isDuplicate && <div style={{ fontSize: 10, color: '#dc2626', fontWeight: 700, marginTop: 2 }}>ΔΙΠΛΗ</div>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, color: '#374151', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                <span>{log.waiter_name ?? (log.waiter_id ? `#${log.waiter_id}` : '—')}</span>
                {log.amount != null && (
                  <span style={{ fontWeight: 700, color: isDuplicate ? '#dc2626' : '#2f9e5e' }}>
                    {fmtEUR(log.amount)}
                  </span>
                )}
                {log.payment_method && <PayMethodChip method={log.payment_method} />}
              </div>
              {itemNames.length > 0 && (
                <div style={{ marginTop: 3, display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                  {itemNames.map((name, i) => (
                    <span key={i} style={{ fontSize: 11, background: '#f3f4f6', color: '#374151', padding: '1px 6px', borderRadius: 4 }}>
                      {name}
                    </span>
                  ))}
                </div>
              )}
            </div>
            <div style={{ fontSize: 11, color: '#9ca3af', textAlign: 'right', flexShrink: 0 }}>
              {displayTime}
              {log.offline_at && <div style={{ fontSize: 10, color: '#f59e0b' }}>offline</div>}
            </div>
          </div>
        )
      })}
    </div>
  )
}

// ── Items tab ───────────────────────────────────────────────────────────────
function ItemsTab({ order, priceEventsMap = {} }) {
  const itemsFiltered = order.items || []
  const billableItems = itemsFiltered.filter(i => i.status !== 'cancelled')
  const effPrice = i => (i.unit_price ?? 0) + (i.price_adjustment ?? 0)
  const closedTotal = billableItems.filter(i => i.status === 'closed').reduce((s, i) => s + effPrice(i) * i.quantity, 0)
  const total = billableItems.reduce((s, i) => s + effPrice(i) * i.quantity, 0)

  if (itemsFiltered.length === 0) {
    return <p style={{ color: '#b8bdc4', fontSize: 13, textAlign: 'center', padding: '12px 0' }}>Κανένα αντικείμενο</p>
  }

  // Column widths: [item info] [ordered by] [paid by] [pay type] [total]
  const GRID = '1fr 150px 150px 110px 80px'

  const EVENT_COLORS = { modifier_applied: '#2563eb', waiter_discount: '#7c3aed', free_item_added: '#16a34a' }

  return (
    <div style={{ borderRadius: 10, border: '1px solid #edeff1', overflow: 'hidden', marginBottom: 16 }}>
      {/* Header */}
      <div style={{ display: 'grid', gridTemplateColumns: GRID, background: '#f9fafb', padding: '6px 14px', fontSize: 10, fontWeight: 700, color: '#8a9099', textTransform: 'uppercase', letterSpacing: 0.4, gap: 12 }}>
        <span>Προϊόν</span>
        <span>Παρήγγειλε</span>
        <span>Πλήρωσε</span>
        <span>Τρόπος</span>
        <span style={{ textAlign: 'right' }}>Σύνολο</span>
      </div>

      {itemsFiltered.map(item => {
        const isCancelled = item.status === 'cancelled'
        const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0)
        const isDealItem = !!item.deal_id
        const itemEvents = (priceEventsMap[item.id] ?? []).filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type))
        return (
          <div key={item.id} style={{ borderTop: '1px solid #f4f4f2', opacity: isCancelled ? 0.45 : 1, background: isCancelled ? '#fef2f2' : item.status === 'closed' ? '#fffbeb' : 'white' }}>
            <div style={{ display: 'grid', gridTemplateColumns: GRID, gap: 12, padding: '9px 14px' }}>
            {/* Item info */}
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: '#111315', textDecoration: isCancelled ? 'line-through' : 'none', display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}>
                {item.product?.name ?? `#${item.product_id}`}
                {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>}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 12, color: '#8a9099', fontFamily: 'ui-monospace,monospace' }}>×{item.quantity}</span>
                <span style={{ fontSize: 12, color: hasPriceAdj ? '#3b82f6' : '#374151', fontFamily: 'ui-monospace,monospace' }}>{fmtEUR(effPrice(item))}</span>
                {hasPriceAdj && (
                  <span style={{ fontSize: 10, color: '#9ca3af', fontFamily: 'ui-monospace,monospace', textDecoration: 'line-through' }}>{fmtEUR(item.unit_price)}</span>
                )}
                <StatusPill status={item.status} />
              </div>
              {itemEvents.map((ev, ei) => {
                const evColor = EVENT_COLORS[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 (
                  <div key={ei} style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2, fontSize: 11, color: evColor }}>
                    <span style={{ opacity: 0.6 }}>↳</span>
                    <span style={{ flex: 1 }}>{evLabel}</span>
                    {ev.delta_amount != null && <span style={{ fontWeight: 600 }}>{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €</span>}
                  </div>
                )
              })}
            </div>

            {/* Ordered by */}
            <div style={{ fontSize: 11, paddingTop: 2 }}>
              <div style={{ fontWeight: 600, color: '#374151' }}>{item.added_by_name ?? '—'}</div>
              {item.added_at && <div style={{ color: '#9ca3af', marginTop: 1 }}>{fmtDateTime(item.added_at)}</div>}
            </div>

            {/* Paid by */}
            <div style={{ fontSize: 11, paddingTop: 2 }}>
              {item.paid_by_name
                ? <>
                    <div style={{ fontWeight: 600, color: '#15803d' }}>{item.paid_by_name}</div>
                    {item.paid_at && <div style={{ color: '#9ca3af', marginTop: 1 }}>{fmtDateTime(item.paid_at)}</div>}
                  </>
                : <span style={{ color: '#b8bdc4' }}>—</span>
              }
            </div>

            {/* Pay type */}
            <div style={{ paddingTop: 2 }}>
              <PayMethodChip method={item.payment_method} />
            </div>

            {/* Total */}
            <div style={{ fontSize: 13, fontWeight: 700, color: hasPriceAdj ? '#3b82f6' : '#111315', textAlign: 'right', fontFamily: 'ui-monospace,monospace', paddingTop: 2 }}>
              {fmtEUR(effPrice(item) * item.quantity)}
            </div>
            </div>
          </div>
        )
      })}

      {/* Totals footer */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', padding: '8px 14px', background: '#f9fafb', borderTop: '1px solid #edeff1', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        {closedTotal > 0 && (
          <span style={{ fontSize: 11, color: '#b45309' }}>
            Απλήρωτα κλειστά: <span style={{ fontWeight: 700 }}>{fmtEUR(closedTotal)}</span>
          </span>
        )}
        <span style={{ fontSize: 11, fontWeight: 700, color: '#8a9099', textTransform: 'uppercase', letterSpacing: 0.4 }}>Σύνολο</span>
        <span style={{ fontSize: 15, fontWeight: 700, color: '#111315', fontFamily: 'ui-monospace,monospace' }}>{fmtEUR(total)}</span>
      </div>
    </div>
  )
}

// ── Main modal ──────────────────────────────────────────────────────────────
export default function OrderDetailModal({ order, onClose }) {
  const [tab, setTab] = useState('items')

  const { data: rawPriceEvents = [] } = useQuery({
    queryKey: ['price-events', order?.id],
    queryFn: () => client.get(`/api/pricing/events/order/${order.id}`).then(r => r.data),
    enabled: !!order?.id,
    staleTime: 60_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
  }, {})

  if (!order) return null

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

  const TABS = [
    { key: 'items', label: `Αντικείμενα (${(order.items || []).length})` },
    { key: 'audit', label: 'Ιστορικό Συναλλαγών' },
  ]

  return (
    <div
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}
      onClick={onClose}
    >
      <div
        style={{ background: 'white', borderRadius: 20, width: '100%', maxWidth: 1032, maxHeight: '92vh', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,0.25)' }}
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div style={{ padding: '18px 24px', borderBottom: '1px solid #edeff1', flexShrink: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, color: '#111315', display: 'flex', alignItems: 'center', gap: 10 }}>
              Παραγγελία #{order.id}
              <StatusPill status={order.status} />
            </div>
            <div style={{ fontSize: 13, color: '#5a6169', marginTop: 3 }}>
              {order.table_name ? `Τραπέζι ${order.table_name}` : order.table_id ? `Τραπέζι #${order.table_id}` : ''}
              {order.notes && <span style={{ marginLeft: 8, color: '#d97706' }}>· Σημ: {order.notes}</span>}
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#8a9099', padding: 4 }}>
            <X size={18} />
          </button>
        </div>

        {/* Opener / closer strip */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: '#edeff1', borderBottom: '1px solid #edeff1', flexShrink: 0 }}>
          {[
            { label: 'Άνοιξε', name: order.opened_by_name, time: order.opened_at },
            { label: 'Έκλεισε', name: order.closed_by_name, time: order.closed_at },
          ].map(cell => (
            <div key={cell.label} style={{ background: 'white', padding: '10px 20px' }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: '#8a9099', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 2 }}>{cell.label}</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: cell.name ? '#111315' : '#b8bdc4' }}>{cell.name ?? '—'}</div>
              {cell.time && <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>{fmtDateTime(cell.time)}</div>}
            </div>
          ))}
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid #edeff1', flexShrink: 0, padding: '0 24px' }}>
          {TABS.map(t => (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              style={{
                padding: '10px 16px', fontSize: 12, fontWeight: 600,
                color: tab === t.key ? '#111315' : '#8a9099',
                borderBottom: tab === t.key ? '2px solid #111315' : '2px solid transparent',
                background: 'none', border: 'none', borderBottom: tab === t.key ? '2px solid #111315' : '2px solid transparent',
                cursor: 'pointer', transition: 'color 0.15s',
              }}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Tab content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 24px' }}>
          {tab === 'items' && <ItemsTab order={order} priceEventsMap={priceEventsMap} />}
          {tab === 'audit' && <AuditTimeline logs={order.audit_logs} itemsById={itemsById} />}
        </div>
      </div>
    </div>
  )
}
