'use client'

import { useEffect, useMemo, useRef, useState } from 'react'
import { flushSync } from 'react-dom'
import { useDebugStore, type DebugRealtimeEvent } from './debug-store'
import { StorePanel } from './store-panel'

type RowType = 'ready' | 'message' | 'error' | 'open' | 'close'

interface Row {
  receivedAt: number
  type: RowType
  raw: string
  parsed?: Record<string, unknown>
}

interface Stats {
  reconnects: number
  totalEvents: number
  firstEventAt: number | null
  lastEventAt: number | null
  largestGapMs: number
  emitInFlight: boolean
  lastEmitResult: string | null
}

const MAX_ROWS = 500
const HEARTBEAT_WARN_MS = 30_000

export function DebugRealtimeClient() {
  const [rows, setRows] = useState<Row[]>([])
  const [status, setStatus] = useState<'connecting' | 'open' | 'closed' | 'error'>('connecting')
  const [stats, setStats] = useState<Stats>({
    reconnects: 0,
    totalEvents: 0,
    firstEventAt: null,
    lastEventAt: null,
    largestGapMs: 0,
    emitInFlight: false,
    lastEmitResult: null,
  })
  const [filterType, setFilterType] = useState<'all' | RowType>('all')
  const [filterEntity, setFilterEntity] = useState<'all' | 'task' | 'story' | 'debug'>('all')
  const [tickNow, setTickNow] = useState(() => Date.now())

  // Layer-toggles — elke combinatie isoleert een potentiële bron van bugs.
  // - dispatchToStore: voert applyEvent uit op een mini Zustand-store
  // - useFlushSync: forceert React om synchroon te renderen tijdens dispatch
  // - useViewTransition: wrap dispatch in document.startViewTransition
  const [dispatchToStore, setDispatchToStore] = useState(true)
  const [useFlushSync, setUseFlushSync] = useState(false)
  const [useViewTransition, setUseViewTransition] = useState(false)
  const dispatchToStoreRef = useRef(dispatchToStore)
  const useFlushSyncRef = useRef(useFlushSync)
  const useViewTransitionRef = useRef(useViewTransition)
  useEffect(() => { dispatchToStoreRef.current = dispatchToStore }, [dispatchToStore])
  useEffect(() => { useFlushSyncRef.current = useFlushSync }, [useFlushSync])
  useEffect(() => { useViewTransitionRef.current = useViewTransition }, [useViewTransition])

  const sourceRef = useRef<EventSource | null>(null)
  const lastEventTimeRef = useRef<number | null>(null)

  // Tick every second om "since last event"-counter levend te houden
  useEffect(() => {
    const t = setInterval(() => setTickNow(Date.now()), 1000)
    return () => clearInterval(t)
  }, [])

  useEffect(() => {
    const append = (row: Row) => {
      setRows((prev) => [row, ...prev].slice(0, MAX_ROWS))
      lastEventTimeRef.current = row.receivedAt
      setStats((s) => {
        const prevLast = s.lastEventAt
        const gap = prevLast ? row.receivedAt - prevLast : 0
        return {
          ...s,
          totalEvents: s.totalEvents + 1,
          firstEventAt: s.firstEventAt ?? row.receivedAt,
          lastEventAt: row.receivedAt,
          largestGapMs: Math.max(s.largestGapMs, gap),
        }
      })
    }

    const open = () => {
      const source = new EventSource('/api/debug/realtime-stream')
      sourceRef.current = source

      append({ receivedAt: Date.now(), type: 'open', raw: '(EventSource opening)' })
      setStats((s) => ({ ...s, reconnects: s.reconnects + 1 }))
      setStatus('connecting')

      source.addEventListener('ready', (e) => {
        setStatus('open')
        const data = (e as MessageEvent).data ?? ''
        const parsed = safeParse(data)
        append({ receivedAt: Date.now(), type: 'ready', raw: data, parsed })
      })

      source.addEventListener('error', (e) => {
        setStatus('error')
        const data = (e as MessageEvent).data ?? '(no data)'
        append({ receivedAt: Date.now(), type: 'error', raw: data })
      })

      source.onmessage = (e) => {
        const parsed = safeParse(e.data ?? '')
        append({ receivedAt: Date.now(), type: 'message', raw: e.data ?? '', parsed })

        // Dispatch naar de mini Zustand-store, optioneel met flushSync
        // en/of startViewTransition om de echte solo-flow te mimeken.
        if (dispatchToStoreRef.current && parsed) {
          const dispatch = () =>
            useDebugStore.getState().applyEvent(parsed as DebugRealtimeEvent)
          const wrapWithFlush = useFlushSyncRef.current
            ? () => flushSync(dispatch)
            : dispatch
          if (
            useViewTransitionRef.current &&
            typeof document !== 'undefined' &&
            typeof (document as Document & { startViewTransition?: unknown })
              .startViewTransition === 'function'
          ) {
            ;(
              document as Document & {
                startViewTransition: (cb: () => void) => unknown
              }
            ).startViewTransition(wrapWithFlush)
          } else {
            wrapWithFlush()
          }
        }
      }

      source.onerror = () => {
        setStatus('error')
        append({ receivedAt: Date.now(), type: 'close', raw: '(EventSource error/close)' })
      }
    }

    open()

    return () => {
      sourceRef.current?.close()
      sourceRef.current = null
    }
  }, [])

  async function emitTestEvent() {
    setStats((s) => ({ ...s, emitInFlight: true, lastEmitResult: null }))
    try {
      const res = await fetch('/api/debug/emit-test-notify', { method: 'POST' })
      const json = (await res.json()) as { ok?: boolean; error?: string }
      setStats((s) => ({
        ...s,
        emitInFlight: false,
        lastEmitResult: json.ok ? 'sent ✓' : `failed: ${json.error ?? 'unknown'}`,
      }))
    } catch (err) {
      setStats((s) => ({
        ...s,
        emitInFlight: false,
        lastEmitResult: `failed: ${err instanceof Error ? err.message : String(err)}`,
      }))
    }
  }

  function reset() {
    setRows([])
    setStats({
      reconnects: 0,
      totalEvents: 0,
      firstEventAt: null,
      lastEventAt: null,
      largestGapMs: 0,
      emitInFlight: false,
      lastEmitResult: null,
    })
    lastEventTimeRef.current = null
  }

  const filteredRows = useMemo(() => {
    return rows.filter((row) => {
      if (filterType !== 'all' && row.type !== filterType) return false
      if (filterEntity !== 'all') {
        const entity = (row.parsed?.entity as string | undefined) ?? null
        if (filterEntity === 'debug') {
          if (!row.parsed?.debug) return false
        } else {
          if (entity !== filterEntity) return false
        }
      }
      return true
    })
  }, [rows, filterType, filterEntity])

  const sinceLastEvent = lastEventTimeRef.current
    ? tickNow - lastEventTimeRef.current
    : null

  return (
    <div style={{ marginTop: 16 }}>
      <ControlBar
        status={status}
        stats={stats}
        sinceLastEvent={sinceLastEvent}
        filterType={filterType}
        setFilterType={setFilterType}
        filterEntity={filterEntity}
        setFilterEntity={setFilterEntity}
        onEmit={emitTestEvent}
        onReset={reset}
      />
      <LayerToggles
        dispatchToStore={dispatchToStore}
        setDispatchToStore={setDispatchToStore}
        useFlushSync={useFlushSync}
        setUseFlushSync={setUseFlushSync}
        useViewTransition={useViewTransition}
        setUseViewTransition={setUseViewTransition}
      />
      {dispatchToStore && <StorePanel />}
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 12 }}>
        <thead>
          <tr style={{ background: '#f0f0f0', textAlign: 'left' }}>
            <th style={{ padding: 6, border: '1px solid #ddd', width: 220 }}>received_at</th>
            <th style={{ padding: 6, border: '1px solid #ddd', width: 100 }}>type</th>
            <th style={{ padding: 6, border: '1px solid #ddd', width: 140 }}>entity / op</th>
            <th style={{ padding: 6, border: '1px solid #ddd' }}>payload</th>
          </tr>
        </thead>
        <tbody>
          {filteredRows.length === 0 ? (
            <tr>
              <td colSpan={4} style={{ padding: 12, textAlign: 'center', color: '#888' }}>
                Wachten op events… trigger een mutatie via UI / script of klik &quot;emit test event&quot;.
              </td>
            </tr>
          ) : (
            filteredRows.map((row, idx) => (
              <tr
                key={`${row.receivedAt}-${idx}`}
                style={{ background: row.type === 'message' ? 'transparent' : '#fafafa' }}
              >
                <td style={{ padding: 6, border: '1px solid #ddd', whiteSpace: 'nowrap' }}>
                  {new Date(row.receivedAt).toISOString()}
                </td>
                <td style={{ padding: 6, border: '1px solid #ddd', color: typeColor(row.type) }}>
                  {row.type}
                </td>
                <td style={{ padding: 6, border: '1px solid #ddd', whiteSpace: 'nowrap' }}>
                  {row.parsed?.entity ? (
                    <>
                      {row.parsed.entity as string}
                      {row.parsed.op ? ` / ${row.parsed.op as string}` : ''}
                      {row.parsed.debug ? ' [debug]' : ''}
                    </>
                  ) : (
                    '—'
                  )}
                </td>
                <td style={{ padding: 6, border: '1px solid #ddd', wordBreak: 'break-all' }}>
                  <code>{row.raw}</code>
                </td>
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  )
}

function ControlBar({
  status,
  stats,
  sinceLastEvent,
  filterType,
  setFilterType,
  filterEntity,
  setFilterEntity,
  onEmit,
  onReset,
}: {
  status: 'connecting' | 'open' | 'closed' | 'error'
  stats: Stats
  sinceLastEvent: number | null
  filterType: 'all' | RowType
  setFilterType: (t: 'all' | RowType) => void
  filterEntity: 'all' | 'task' | 'story' | 'debug'
  setFilterEntity: (e: 'all' | 'task' | 'story' | 'debug') => void
  onEmit: () => void
  onReset: () => void
}) {
  const heartbeatStale = sinceLastEvent !== null && sinceLastEvent > HEARTBEAT_WARN_MS
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
          gap: 8,
          padding: 12,
          background: '#f7f7f7',
          border: '1px solid #ddd',
          borderRadius: 4,
        }}
      >
        <Stat label="status" value={status} color={statusColor(status)} />
        <Stat label="reconnects" value={String(stats.reconnects)} />
        <Stat label="total events" value={String(stats.totalEvents)} />
        <Stat
          label="since last event"
          value={sinceLastEvent === null ? '—' : `${(sinceLastEvent / 1000).toFixed(1)}s`}
          color={heartbeatStale ? 'red' : undefined}
        />
        <Stat
          label="largest gap"
          value={
            stats.largestGapMs > 0
              ? `${(stats.largestGapMs / 1000).toFixed(1)}s`
              : '—'
          }
        />
        <Stat
          label="first event"
          value={stats.firstEventAt ? new Date(stats.firstEventAt).toLocaleTimeString() : '—'}
        />
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        <button
          onClick={onEmit}
          disabled={stats.emitInFlight}
          style={{
            padding: '6px 12px',
            background: '#0a0',
            color: 'white',
            border: 'none',
            borderRadius: 4,
            cursor: stats.emitInFlight ? 'wait' : 'pointer',
            opacity: stats.emitInFlight ? 0.6 : 1,
          }}
        >
          {stats.emitInFlight ? 'sending…' : 'emit test event'}
        </button>
        {stats.lastEmitResult && (
          <span style={{ fontSize: 12, color: '#666' }}>{stats.lastEmitResult}</span>
        )}
        <button
          onClick={onReset}
          style={{
            padding: '6px 12px',
            background: '#eee',
            border: '1px solid #ccc',
            borderRadius: 4,
            cursor: 'pointer',
          }}
        >
          reset stats
        </button>
        <span style={{ marginLeft: 12, fontSize: 12, color: '#666' }}>filter:</span>
        <select
          value={filterType}
          onChange={(e) => setFilterType(e.target.value as 'all' | RowType)}
          style={{ fontSize: 12, padding: 4 }}
        >
          <option value="all">all types</option>
          <option value="ready">ready</option>
          <option value="message">message</option>
          <option value="error">error</option>
          <option value="open">open</option>
          <option value="close">close</option>
        </select>
        <select
          value={filterEntity}
          onChange={(e) => setFilterEntity(e.target.value as 'all' | 'task' | 'story' | 'debug')}
          style={{ fontSize: 12, padding: 4 }}
        >
          <option value="all">all entities</option>
          <option value="task">task</option>
          <option value="story">story</option>
          <option value="debug">debug only</option>
        </select>
      </div>
    </div>
  )
}

function LayerToggles({
  dispatchToStore,
  setDispatchToStore,
  useFlushSync,
  setUseFlushSync,
  useViewTransition,
  setUseViewTransition,
}: {
  dispatchToStore: boolean
  setDispatchToStore: (v: boolean) => void
  useFlushSync: boolean
  setUseFlushSync: (v: boolean) => void
  useViewTransition: boolean
  setUseViewTransition: (v: boolean) => void
}) {
  return (
    <div
      style={{
        marginTop: 12,
        padding: 8,
        background: '#fff8e1',
        border: '1px solid #ffe0a0',
        borderRadius: 4,
        fontSize: 12,
      }}
    >
      <strong style={{ marginRight: 12 }}>Layers:</strong>
      <label style={{ marginRight: 16 }}>
        <input
          type="checkbox"
          checked={dispatchToStore}
          onChange={(e) => setDispatchToStore(e.target.checked)}
        />{' '}
        dispatch naar mini-store
      </label>
      <label style={{ marginRight: 16 }}>
        <input
          type="checkbox"
          checked={useFlushSync}
          onChange={(e) => setUseFlushSync(e.target.checked)}
          disabled={!dispatchToStore}
        />{' '}
        wrap in flushSync
      </label>
      <label>
        <input
          type="checkbox"
          checked={useViewTransition}
          onChange={(e) => setUseViewTransition(e.target.checked)}
          disabled={!dispatchToStore}
        />{' '}
        wrap in startViewTransition
      </label>
    </div>
  )
}

function Stat({ label, value, color }: { label: string; value: string; color?: string }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <span style={{ fontSize: 11, color: '#888', textTransform: 'uppercase' }}>{label}</span>
      <span style={{ fontSize: 14, fontWeight: 'bold', color: color ?? 'inherit' }}>{value}</span>
    </div>
  )
}

function statusColor(status: 'connecting' | 'open' | 'closed' | 'error') {
  switch (status) {
    case 'open':
      return 'green'
    case 'error':
      return 'red'
    case 'closed':
      return 'gray'
    default:
      return 'orange'
  }
}

function typeColor(type: RowType) {
  switch (type) {
    case 'message':
      return '#0070cc'
    case 'ready':
      return 'green'
    case 'error':
      return 'red'
    case 'open':
      return '#888'
    case 'close':
      return '#888'
  }
}

function safeParse(raw: string): Record<string, unknown> | undefined {
  try {
    return JSON.parse(raw) as Record<string, unknown>
  } catch {
    return undefined
  }
}
