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'

function fmtDur(ms) {
  const totalMin = Math.round(ms / 60000)
  const h = Math.floor(totalMin / 60)
  const m = totalMin % 60
  return h > 0 ? `${h}ω ${m}λ` : `${m}λ`
}

// ── Breaks timeline bar ──────────────────────────────────────────────────────
function BreaksTimeline({ started_at, ended_at, breaks }) {
  if (!breaks || breaks.length === 0) return null

  const start = new Date(started_at).getTime()
  const end = ended_at ? new Date(ended_at).getTime() : Date.now()
  const total = end - start
  if (total <= 0) return null

  return (
    <div style={{ padding: '10px 24px 12px', background: '#fafafa', borderBottom: '1px solid #edeff1', flexShrink: 0 }}>
      <div style={{ fontSize: 10, fontWeight: 700, color: '#8a9099', textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 6 }}>
        Διαλείμματα
      </div>
      <div style={{ position: 'relative', height: 8, borderRadius: 4, background: '#e2e8f0', overflow: 'hidden' }}>
        {/* work = whole bar base */}
        {breaks.map((b, i) => {
          const bs = new Date(b.started_at).getTime()
          const be = b.ended_at ? new Date(b.ended_at).getTime() : Date.now()
          const left = Math.max(0, ((bs - start) / total) * 100)
          const width = Math.min(100 - left, ((be - bs) / total) * 100)
          return (
            <div
              key={b.id}
              title={`Διάλειμμα ${fmtTime(b.started_at)} – ${b.ended_at ? fmtTime(b.ended_at) : 'ενεργό'} · Διάρκεια: ${fmtDur(be - bs)}`}
              style={{
                position: 'absolute', top: 0, height: '100%',
                left: `${left}%`, width: `${width}%`,
                background: '#f59e0b', borderRadius: 2,
              }}
            />
          )
        })}
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 16px', marginTop: 6 }}>
        {breaks.map(b => {
          const bs = new Date(b.started_at).getTime()
          const be = b.ended_at ? new Date(b.ended_at).getTime() : Date.now()
          return (
            <span key={b.id} style={{ fontSize: 11, color: '#5a6169' }}>
              <span style={{ color: '#b45309', fontWeight: 700 }}>◼</span>{' '}
              {fmtTime(b.started_at)} – {b.ended_at ? fmtTime(b.ended_at) : 'ενεργό'} · {fmtDur(be - bs)}
            </span>
          )
        })}
      </div>
    </div>
  )
}

// ── Order-status distribution bar ───────────────────────────────────────────
function StatusDistributionBar({ counts }) {
  const total = counts.all || 1
  const segments = [
    { key: 'both',      color: '#16a34a', label: 'Πλήρης'      },
    { key: 'paid',      color: '#2563eb', label: 'Πληρώθηκε'   },
    { key: 'ordered',   color: '#ca8a04', label: 'Παρήγγειλε'  },
    { key: 'unpaid',    color: '#ea580c', label: 'Ανοιχτό'     },
    { key: 'cancelled', color: '#dc2626', label: 'Ακύρωση'     },
  ].filter(s => counts[s.key] > 0)

  if (segments.length === 0) return null

  return (
    <div style={{ marginTop: 10 }}>
      {/* bar */}
      <div style={{ display: 'flex', height: 8, borderRadius: 4, overflow: 'hidden', gap: 1 }}>
        {segments.map(s => (
          <div
            key={s.key}
            title={`${s.label}: ${counts[s.key]} (${Math.round(counts[s.key] / total * 100)}%)`}
            style={{ flex: counts[s.key], background: s.color, minWidth: 2 }}
          />
        ))}
      </div>
      {/* legend with % */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 14px', marginTop: 6 }}>
        {segments.map(s => (
          <span key={s.key} style={{ fontSize: 10, color: '#5a6169', display: 'flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: s.color, flexShrink: 0, display: 'inline-block' }} />
            {s.label}: {counts[s.key]} ({Math.round(counts[s.key] / total * 100)}%)
          </span>
        ))}
      </div>
    </div>
  )
}

// ── colour rules ────────────────────────────────────────────────────────────
function classify(item, shiftWaiterId) {
  if (item.status === 'cancelled')
    return { key: 'cancelled', label: 'Ακυρώθηκε', dot: '#dc2626', bg: '#fef2f2', border: '#fecaca', text: '#991b1b' }

  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' }
  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: 'Ανοιχτό ακόμη' },
  { key: 'cancelled', label: 'Ακυρώθηκε' },
  { key: 'anomaly',   label: 'Πρόβλημα' },
]

const LEGEND = [
  { dot: '#16a34a', label: 'Πλήρης Παραγγελία' },
  { dot: '#2563eb', label: 'Μόνο Πληρώθηκε' },
  { dot: '#ca8a04', label: 'Μόνο Παρήγγειλε' },
  { dot: '#ea580c', label: 'Ανοιχτό ακόμη' },
  { dot: '#dc2626', 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)
  const isCancelled = item.status === 'cancelled'
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 10, padding: '7px 14px',
      borderTop: '1px solid #f4f4f2', background: c.bg,
    }}>
      <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: isCancelled ? '#991b1b' : '#111315' }}>
            {item.product_name}
            <span style={{ fontWeight: 400, color: '#8a9099', marginLeft: 4 }}>×{item.quantity}</span>
          </span>
          <span style={{ fontSize: 13, fontWeight: 700, color: isCancelled ? '#b91c1c' : '#111315', flexShrink: 0, textDecoration: isCancelled ? 'line-through' : 'none' }}>
            {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>
          {!isCancelled && (
            <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' }}>
      <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,
  })

  const counts = { all: 0, both: 0, paid: 0, ordered: 0, unpaid: 0, cancelled: 0, anomaly: 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: 1080,
        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 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'
                  : discrepancy > 0
                    ? '#16a34a'  // surplus → green
                    : '#dc2626'  // shortage → red

              const cancelEvents = summary.cancellation_events ?? 0
              const cancelItemsQty = summary.orders
                ? summary.orders.reduce((s, o) => s + o.items.filter(i => i.status === 'cancelled').reduce((ss, i) => ss + i.quantity, 0), 0)
                : 0

              const cashSales = summary.cash_sales ?? summary.total_collected ?? 0
              const cardSales = summary.card_sales ?? 0
              const totalRev  = cashSales + cardSales
              const collectLabel = cardSales > 0
                ? `${fmtEUR(cashSales)} + ${fmtEUR(cardSales)}`
                : fmtEUR(cashSales)

              const row2 = [
                { label: 'Σύνολο Παραγγελιών', value: String(totalOrders) },
                { label: 'Εισπράξεις (μετρητά + κάρτα)', value: collectLabel, accent: '#2f9e5e' },
                {
                  label: 'Ακυρώσεις',
                  value: cancelEvents > 0 ? `${cancelEvents} / ${cancelItemsQty} είδη` : '—',
                  accent: cancelEvents > 0 ? '#dc2626' : undefined,
                },
                { 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>
              )
            })()}

            {/* Breaks timeline (hidden when no breaks) */}
            <BreaksTimeline
              started_at={summary.started_at}
              ended_at={summary.ended_at}
              breaks={summary.breaks || []}
            />

            {/* Status distribution bar */}
            <div style={{ padding: '8px 24px 10px', background: '#fafafa', borderBottom: '1px solid #edeff1', flexShrink: 0 }}>
              <StatusDistributionBar counts={counts} />
            </div>

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