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

// ── colour rules ────────────────────────────────────────────────────────────
// Given the shift's waiter_id and one item, return { key, label, colors }
function classify(item, shiftWaiterId) {
  const orderedByMe = item.added_by_id === shiftWaiterId
  const paidToMe    = item.paid_by_id  === shiftWaiterId
  const isPaid      = item.status === 'paid'

  if (orderedByMe && paidToMe && isPaid)
    return { key: 'both',    label: 'Παρήγγειλε + Πληρώθηκε', dot: '#16a34a', bg: '#f0fdf4', border: '#bbf7d0', text: '#15803d' }
  if (!orderedByMe && paidToMe && isPaid)
    return { key: 'paid',    label: 'Πληρώθηκε (άλλος παρήγγειλε)', dot: '#2563eb', bg: '#eff6ff', border: '#bfdbfe', text: '#1d4ed8' }
  if (orderedByMe && isPaid && !paidToMe)
    return { key: 'ordered', label: 'Παρήγγειλε (Πληρώθηκε άλλος)', dot: '#ca8a04', bg: '#fefce8', border: '#fef08a', text: '#854d0e' }
  if (orderedByMe && !isPaid)
    return { key: 'unpaid',  label: 'Παρήγγειλε (απλήρωτο)', dot: '#ea580c', bg: '#fff7ed', border: '#fed7aa', text: '#c2410c' }
  // fallback: paid to me but status not 'paid' — data anomaly
  return { key: 'anomaly', label: 'Ανωμαλία δεδομένων', dot: '#dc2626', bg: '#fef2f2', border: '#fecaca', text: '#b91c1c' }
}

const FILTER_OPTIONS = [
  { key: 'all',     label: 'Όλα' },
  { key: 'both',    label: 'Παρήγγειλε + Πληρώθηκε' },
  { key: 'paid',    label: 'Πληρώθηκε (ξένη παραγγελία)' },
  { key: 'ordered', label: 'Παρήγγειλε (Πληρώθηκε άλλος)' },
  { key: 'unpaid',  label: 'Απλήρωτα' },
]

function fmtMins(mins) {
  if (mins == null) return '—'
  const h = Math.floor(mins / 60)
  const m = mins % 60
  return h > 0 ? `${h}ω ${m}λ` : `${m}λ`
}

function ItemRow({ item, shiftWaiterId }) {
  const c = classify(item, shiftWaiterId)
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 10, padding: '7px 14px',
      borderTop: '1px solid #f4f4f2', background: c.bg,
    }}>
      {/* colour dot */}
      <div style={{ width: 8, height: 8, borderRadius: '50%', background: c.dot, flexShrink: 0, marginTop: 5 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: '#111315' }}>
            {item.product_name}
            <span style={{ fontWeight: 400, color: '#8a9099', marginLeft: 4 }}>×{item.quantity}</span>
          </span>
          <span style={{ fontSize: 13, fontWeight: 700, color: '#111315', flexShrink: 0 }}>{fmtEUR(item.subtotal)}</span>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2px 12px', marginTop: 2 }}>
          <span style={{ fontSize: 11, color: '#5a6169' }}>
            Παρήγγειλε: <span style={{ fontWeight: 600, color: '#374151' }}>{item.added_by_name ?? '—'}</span>
            {item.added_at ? <span style={{ color: '#9ca3af' }}> · {fmtDateTime(item.added_at)}</span> : null}
          </span>
          <span style={{ fontSize: 11, color: '#5a6169' }}>
            Πληρώθηκε: <span style={{ fontWeight: 600, color: item.paid_by_name ? '#374151' : '#9ca3af' }}>{item.paid_by_name ?? '—'}</span>
            {item.paid_at ? <span style={{ color: '#9ca3af' }}> · {fmtDateTime(item.paid_at)}</span> : null}
            {item.payment_method ? <span style={{ color: '#9ca3af' }}> ({item.payment_method})</span> : null}
          </span>
        </div>
        <div style={{ marginTop: 2 }}>
          <span style={{
            fontSize: 10, fontWeight: 600, padding: '1px 6px', borderRadius: 4,
            background: c.border, color: c.text, border: `1px solid ${c.border}`,
          }}>{c.label}</span>
        </div>
      </div>
    </div>
  )
}

function OrderGroup({ order, shiftWaiterId, activeFilter }) {
  const visibleItems = order.items.filter(item => {
    if (activeFilter === 'all') return true
    return classify(item, shiftWaiterId).key === activeFilter
  })
  if (visibleItems.length === 0) return null

  const groupTotal = visibleItems
    .filter(i => i.status === 'paid')
    .reduce((s, i) => s + i.subtotal, 0)

  return (
    <div style={{ borderRadius: 10, border: '1px solid #edeff1', marginBottom: 8, overflow: 'hidden' }}>
      {/* Order header */}
      <div style={{ padding: '8px 14px', background: '#f9fafb', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 4 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: '#374151' }}>
          Παραγγελία #{order.order_id}
          {order.table_name && <span style={{ color: '#8a9099', fontWeight: 400, marginLeft: 6 }}>· Τραπέζι {order.table_name}</span>}
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          {order.opener_name && (
            <span style={{ fontSize: 11, color: '#5a6169' }}>
              Άνοιξε: <span style={{ fontWeight: 600, color: '#374151' }}>{order.opener_name}</span>
              {order.opened_at ? <span style={{ color: '#9ca3af' }}> {fmtTime(order.opened_at)}</span> : null}
            </span>
          )}
          {order.closer_name && (
            <span style={{ fontSize: 11, color: '#5a6169' }}>
              Έκλεισε: <span style={{ fontWeight: 600, color: '#374151' }}>{order.closer_name}</span>
              {order.closed_at ? <span style={{ color: '#9ca3af' }}> {fmtTime(order.closed_at)}</span> : null}
            </span>
          )}
          {groupTotal > 0 && (
            <span style={{ fontSize: 12, fontWeight: 700, color: '#2f9e5e' }}>{fmtEUR(groupTotal)}</span>
          )}
        </div>
      </div>
      {visibleItems.map(item => (
        <ItemRow key={item.id} item={item} shiftWaiterId={shiftWaiterId} />
      ))}
    </div>
  )
}

export default function ShiftDetailModal({ shiftId, shiftWaiterId, onClose }) {
  const [activeFilter, setActiveFilter] = useState('all')

  const { data: summary, isLoading, isError } = useQuery({
    queryKey: ['shift-detail', shiftId],
    queryFn: () => client.get(`/api/shifts/${shiftId}/summary`).then(r => r.data),
    staleTime: 30 * 1000,
  })

  // Count items per filter key for badge counts
  const counts = { all: 0, both: 0, paid: 0, ordered: 0, unpaid: 0 }
  const waiterIdToUse = shiftWaiterId ?? summary?.waiter_id
  if (summary?.orders) {
    for (const o of summary.orders) {
      for (const item of o.items) {
        counts.all++
        const key = classify(item, waiterIdToUse).key
        if (key in counts) counts[key]++
      }
    }
  }

  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: 900,
        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' }}>Λεπτομέρειες Βάρδιας</div>
            {summary && (
              <div style={{ fontSize: 13, color: '#5a6169', marginTop: 2 }}>
                {summary.waiter_name} · {fmtDate(summary.started_at)} · {fmtTime(summary.started_at)}–{summary.ended_at ? fmtTime(summary.ended_at) : 'ενεργή'}
              </div>
            )}
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#8a9099', padding: 4 }}>
            <X size={18} />
          </button>
        </div>

        {isLoading && <div style={{ padding: 40, textAlign: 'center', color: '#8a9099' }}>Φόρτωση…</div>}
        {isError && <div style={{ padding: 40, textAlign: 'center', color: '#dc2626' }}>Σφάλμα φόρτωσης δεδομένων</div>}

        {summary && (
          <>
            {/* KPI grid — 2 rows × 4 cols */}
            {(() => {
              const totalOrders = summary.orders?.length ?? 0
              const tableSet = new Set(summary.orders?.map(o => o.table_name).filter(Boolean))
              const tablesServed = tableSet.size
              const durationHours = summary.duration_hours ?? (summary.duration_minutes != null ? summary.duration_minutes / 60 : null)
              const durationLabel = durationHours != null
                ? (() => { const h = Math.floor(durationHours); const m = Math.round((durationHours - h) * 60); return h > 0 ? `${h}ω ${m}λ` : `${m}λ` })()
                : fmtMins(summary.duration_minutes)
              const row1 = [
                { label: 'Διάρκεια Βάρδιας', value: durationLabel },
                { label: 'Μισθός / Ώρα',      value: summary.hourly_rate_snapshot != null ? fmtEUR(summary.hourly_rate_snapshot) : '—' },
                { label: 'Πληρωμή Βάρδιας',   value: summary.shift_pay != null ? fmtEUR(summary.shift_pay) : 'Δεν παρακολουθείται', accent: summary.shift_pay != null ? '#059669' : undefined },
                { label: 'Αρχικά Μετρητά',    value: summary.starting_cash != null ? fmtEUR(summary.starting_cash) : '—' },
              ]
              const discrepancy = summary.cash_discrepancy
              const discLabel = discrepancy == null
                ? '—'
                : Math.abs(discrepancy) < 0.005
                  ? '✓ Εντάξει'
                  : discrepancy < 0
                    ? `Έλλειμμα ${fmtEUR(Math.abs(discrepancy))}`
                    : `Πλεόνασμα ${fmtEUR(discrepancy)}`
              const discAccent = discrepancy == null
                ? undefined
                : Math.abs(discrepancy) < 0.005 ? '#16a34a' : '#dc2626'

              const row2 = [
                { label: 'Σύνολο Παραγγελιών', value: String(totalOrders) },
                { label: 'Εισπράξεις',          value: fmtEUR(summary.total_collected), accent: '#2f9e5e' },
                { label: 'Παραδόθηκαν',          value: summary.counted_cash_end != null ? fmtEUR(summary.counted_cash_end) : '—', accent: '#3758c9' },
                { label: 'Ταμείο',               value: discLabel, accent: discAccent },
              ]
              return (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: '14px 24px', borderBottom: '1px solid #edeff1', flexShrink: 0 }}>
                  {[row1, row2].map((row, ri) => (
                    <div key={ri} style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 6 }}>
                      {row.map(k => (
                        <div key={k.label} style={{ background: '#f9fafb', borderRadius: 10, padding: '10px 12px', textAlign: 'center' }}>
                          <div style={{ fontSize: 10, fontWeight: 700, color: '#8a9099', textTransform: 'uppercase', letterSpacing: 0.5 }}>{k.label}</div>
                          <div style={{ fontSize: 16, fontWeight: 700, color: k.accent || '#111315', fontFamily: 'ui-monospace,monospace', marginTop: 4 }}>{k.value}</div>
                        </div>
                      ))}
                    </div>
                  ))}
                </div>
              )
            })()}

            {/* Colour legend */}
            <div style={{ display: 'flex', gap: 12, padding: '8px 24px', background: '#fafafa', borderBottom: '1px solid #edeff1', flexShrink: 0, flexWrap: 'wrap' }}>
              {[
                { dot: '#16a34a', label: 'Παρήγγειλε + Πληρώθηκε' },
                { dot: '#2563eb', label: 'Πληρώθηκε (παρήγγηλε άλλος)' },
                { dot: '#ca8a04', label: 'Παρήγγειλε (Πληρώθηκε άλλος)' },
                { dot: '#ea580c', label: 'Παρήγγειλε (απλήρωτο)' },
                { dot: '#dc2626', label: 'Πρόβλημα Δεδομένων' },
              ].map(l => (
                <div key={l.dot} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#5a6169' }}>
                  <div style={{ width: 8, height: 8, borderRadius: '50%', background: l.dot, flexShrink: 0 }} />
                  {l.label}
                </div>
              ))}
            </div>

            {/* Filter bar */}
            <div style={{ display: 'flex', gap: 6, padding: '10px 24px', borderBottom: '1px solid #edeff1', flexShrink: 0, overflowX: 'auto' }}>
              {FILTER_OPTIONS.map(opt => (
                <button
                  key={opt.key}
                  onClick={() => setActiveFilter(opt.key)}
                  style={{
                    padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
                    border: activeFilter === opt.key ? '1.5px solid #3758c9' : '1.5px solid #e5e7eb',
                    background: activeFilter === opt.key ? '#eff6ff' : 'white',
                    color: activeFilter === opt.key ? '#3758c9' : '#5a6169',
                  }}
                >
                  {opt.label}
                  {counts[opt.key] > 0 && (
                    <span style={{
                      marginLeft: 5, padding: '1px 5px', borderRadius: 8, fontSize: 10,
                      background: activeFilter === opt.key ? '#3758c9' : '#e5e7eb',
                      color: activeFilter === opt.key ? 'white' : '#5a6169',
                    }}>
                      {counts[opt.key]}
                    </span>
                  )}
                </button>
              ))}
            </div>

            {/* Orders + items */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '14px 24px' }}>
              {summary.orders.length === 0 ? (
                <p style={{ color: '#b8bdc4', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>
                  Δεν υπάρχουν αντικείμενα για αυτή τη βάρδια
                </p>
              ) : (
                summary.orders.map(o => (
                  <OrderGroup key={o.order_id} order={o} shiftWaiterId={waiterIdToUse} activeFilter={activeFilter} />
                ))
              )}
              {summary.orders.length > 0 &&
                !summary.orders.some(o => o.items.some(i =>
                  activeFilter === 'all' || classify(i, waiterIdToUse).key === activeFilter
                )) && (
                <p style={{ color: '#b8bdc4', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>
                  Δεν υπάρχουν αντικείμενα για αυτό το φίλτρο
                </p>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  )
}
