import { useQuery } from '@tanstack/react-query'
import AppShell from '../components/AppShell'
import client from '../api/client'

// ── helpers ───────────────────────────────────────────────────────────────────

function fmtTime(iso) {
  if (!iso) return '—'
  return new Date(iso).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}

function fmtDuration(seconds) {
  if (seconds == null || seconds < 0) return '—'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (h === 0) return `${m}λ`
  if (m === 0) return `${h}ω`
  return `${h}ω ${m}λ`
}

function fmtEuro(n) {
  return '€' + parseFloat(n || 0).toFixed(2)
}

function sinceSeconds(isoStart) {
  if (!isoStart) return 0
  return Math.floor((Date.now() - new Date(isoStart).getTime()) / 1000)
}

function breakDurationSeconds(b) {
  if (!b.started_at) return 0
  const end = b.ended_at ? new Date(b.ended_at) : new Date()
  return Math.floor((end - new Date(b.started_at)) / 1000)
}

// ── stat card ─────────────────────────────────────────────────────────────────

function StatCard({ label, value, sub, accent }) {
  return (
    <div style={{
      background: 'var(--bg2)', border: '1px solid var(--border)',
      borderRadius: 16, padding: '16px 18px',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.7 }}>{label}</div>
      <div style={{
        fontSize: 28, fontWeight: 700, lineHeight: 1.1,
        color: accent || 'var(--text)',
        fontFamily: "'ui-monospace','SFMono-Regular',monospace",
      }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--muted)' }}>{sub}</div>}
    </div>
  )
}

// ── horizontal bar chart (per-hour) ──────────────────────────────────────────

function PerHourChart({ title, data, accent = 'var(--accent)' }) {
  const hours = Object.keys(data).map(Number).sort((a, b) => a - b)
  if (hours.length === 0) return null
  const maxValue = Math.max(...hours.map(h => data[h]), 1)

  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {hours.map(h => {
          const pct = (data[h] / maxValue) * 100
          return (
            <div key={h} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 32, fontSize: 11, fontWeight: 700, color: 'var(--muted)', textAlign: 'right', flexShrink: 0 }}>
                {String(h).padStart(2, '0')}:00
              </div>
              <div style={{ flex: 1, height: 20, background: 'var(--bg3)', borderRadius: 4, overflow: 'hidden' }}>
                <div style={{
                  height: '100%', borderRadius: 4,
                  width: `${Math.max(pct, data[h] > 0 ? 2 : 0)}%`,
                  background: accent,
                  transition: 'width 300ms ease',
                  display: 'flex', alignItems: 'center',
                }}>
                  {pct > 18 && (
                    <span style={{ fontSize: 10, fontWeight: 800, color: 'var(--accent-fg)', paddingLeft: 6 }}>
                      {data[h]}
                    </span>
                  )}
                </div>
              </div>
              <div style={{ width: 20, fontSize: 11, fontWeight: 700, color: 'var(--text)', flexShrink: 0 }}>
                {pct <= 18 ? data[h] : ''}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ── breaks timeline ───────────────────────────────────────────────────────────

function BreakRow({ brk, index }) {
  const dur = breakDurationSeconds(brk)
  const active = !brk.ended_at
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 14px', borderRadius: 10,
      background: active ? 'rgba(251,146,60,0.1)' : 'var(--bg2)',
      border: `1px solid ${active ? '#f97316' : 'var(--border)'}`,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8, flexShrink: 0,
        background: active ? '#f97316' : 'var(--bg3)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, fontWeight: 700, color: active ? 'white' : 'var(--muted)',
      }}>{index + 1}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
          {fmtTime(brk.started_at)} – {active ? 'Τώρα' : fmtTime(brk.ended_at)}
        </div>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 1 }}>
          {fmtDuration(dur)}
        </div>
      </div>
      {active && (
        <span style={{
          fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999,
          background: '#f97316', color: 'white',
        }}>ΕΝΕΡΓΟ</span>
      )}
    </div>
  )
}

// ── main page ─────────────────────────────────────────────────────────────────

export default function ShiftOverviewPage() {
  const { data: shift, isLoading: shiftLoading } = useQuery({
    queryKey: ['my-shift'],
    queryFn: () => client.get('/api/shifts/my').then(r => r.data),
    refetchInterval: 30_000,
  })

  const { data: settings } = useQuery({
    queryKey: ['pos-settings'],
    queryFn: () => client.get('/api/settings/').then(r => r.data),
    staleTime: 60_000,
  })

  const hideRevenue = settings?.['shifts.hide_revenue_from_waiters']?.value === 'true'

  // /api/orders/my returns only open orders belonging to this waiter —
  // enough for per-hour chart of current open tables
  const { data: openOrders = [] } = useQuery({
    queryKey: ['my-orders-shift'],
    queryFn: () => client.get('/api/orders/my').then(r => r.data),
    refetchInterval: 30_000,
    enabled: !!shift,
  })

  if (shiftLoading) {
    return (
      <AppShell title="Shift Overview">
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: 14 }}>
          Φόρτωση…
        </div>
      </AppShell>
    )
  }

  if (!shift) {
    return (
      <AppShell title="Shift Overview">
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, padding: 24, textAlign: 'center' }}>
          <div style={{ fontSize: 40 }}>⏸</div>
          <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>Δεν υπάρχει ενεργή βάρδια</div>
          <div style={{ fontSize: 13, color: 'var(--muted)' }}>Ξεκινήστε βάρδια για να δείτε στατιστικά.</div>
        </div>
      </AppShell>
    )
  }

  // ── Compute stats ────────────────────────────────────────────────────────────

  const totalShiftSec = sinceSeconds(shift.started_at)
  const totalBreakSec = (shift.breaks || []).reduce((s, b) => s + breakDurationSeconds(b), 0)
  const workedSec = Math.max(0, totalShiftSec - totalBreakSec)

  // Per-hour buckets from currently-open orders
  const ordersByHour = {}
  const itemsByHour = {}
  openOrders.forEach(o => {
    const h = new Date(o.opened_at).getHours()
    ordersByHour[h] = (ordersByHour[h] || 0) + 1
    itemsByHour[h] = (itemsByHour[h] || 0) +
      (o.items || []).filter(i => i.status !== 'cancelled').reduce((s, i) => s + i.quantity, 0)
  })

  const totalItems = openOrders.reduce((s, o) =>
    s + (o.items || []).filter(i => i.status !== 'cancelled').reduce((is, i) => is + i.quantity, 0), 0)

  const activeBreak = (shift.breaks || []).find(b => !b.ended_at)

  return (
    <AppShell title="Shift Overview">
      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 16px 24px' }}>

        {/* Active break banner */}
        {activeBreak && (
          <div style={{
            margin: '0 0 16px',
            padding: '12px 16px',
            borderRadius: 12,
            background: 'rgba(251,146,60,0.12)',
            border: '1px solid #f97316',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <span style={{ fontSize: 20 }}>☕</span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#f97316' }}>Σε διάλειμμα</div>
              <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>
                από {fmtTime(activeBreak.started_at)} · {fmtDuration(breakDurationSeconds(activeBreak))} μέχρι τώρα
              </div>
            </div>
          </div>
        )}

        {/* Hero stats grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 20 }}>
          <StatCard label="Έναρξη" value={fmtTime(shift.started_at)} />
          <StatCard label="Ώρες Εργασίας" value={fmtDuration(workedSec)} sub={`${fmtDuration(totalBreakSec)} διαλείμματα`} />
          <StatCard label="Αρχ. Μετρητά" value={fmtEuro(shift.starting_cash)} />
          {!hideRevenue && (
            <StatCard label="Είσπραξη" value={fmtEuro(shift.total_collected)} accent="var(--success, #22c55e)" />
          )}
          {!hideRevenue && (
            <StatCard label="Παραδ. Ποσό" value={fmtEuro(shift.net_to_deliver)} sub="Αρχ. + Είσπραξη" accent="var(--accent)" />
          )}
          <StatCard label="Ανοιχτά Τραπέζια" value={String(openOrders.length)} sub="τρέχουσες παραγγελίες" />
          <StatCard label="Είδη (ανοιχτά)" value={String(totalItems)} />
          <StatCard label="Διαλείμματα" value={String((shift.breaks || []).length)} sub={`${fmtDuration(totalBreakSec)} σύνολο`} />
        </div>

        {/* Per-hour charts */}
        {openOrders.length > 0 && (
          <div style={{
            background: 'var(--bg2)', border: '1px solid var(--border)',
            borderRadius: 16, padding: '16px 18px', marginBottom: 20,
          }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)', marginBottom: 16 }}>Ανά Ώρα</div>
            <PerHourChart title="Παραγγελίες" data={ordersByHour} />
            <PerHourChart title="Είδη" data={itemsByHour} />
          </div>
        )}

        {/* Breaks */}
        {(shift.breaks || []).length > 0 && (
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>
              Διαλείμματα ({shift.breaks.length})
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {shift.breaks.map((b, i) => <BreakRow key={b.id} brk={b} index={i} />)}
            </div>
          </div>
        )}
      </div>
    </AppShell>
  )
}
