'use client'

import { useCallback, useEffect, useState, type ReactElement } from 'react'
import type { LogEvent, MetaTag, ParsedRunLog } from '@/lib/parse-worker-log'
import { cn, formatDuration } from '@/lib/utils'

async function fetchDetail(fileName: string): Promise<ParsedRunLog> {
  const res = await fetch(`/api/worker-logs/${encodeURIComponent(fileName)}`, { cache: 'no-store' })
  const body = await res.json().catch(() => ({}))
  if (!res.ok) throw new Error(body?.error ?? `request failed (${res.status})`)
  return body as ParsedRunLog
}

const META_TAG_STYLES: Record<MetaTag, string> = {
  claim: 'text-muted-foreground',
  auth: 'text-muted-foreground',
  quota: 'text-muted-foreground',
  'no-job': 'text-muted-foreground',
  claimed: 'text-blue-600 dark:text-blue-400',
  worktree: 'text-muted-foreground',
  config: 'text-blue-600 dark:text-blue-400',
  payload: 'text-muted-foreground',
  spawn: 'text-blue-600 dark:text-blue-400',
  'claude-done': 'text-blue-600 dark:text-blue-400',
  cleanup: 'text-muted-foreground',
  exit: 'text-muted-foreground',
  error: 'text-destructive',
  'token-expired': 'text-destructive',
  timeout: 'text-muted-foreground',
  other: 'text-muted-foreground',
}

function timeOnly(ts: string | null): string {
  if (!ts) return ''
  const d = new Date(ts)
  return isNaN(d.getTime()) ? '' : d.toLocaleTimeString()
}

function inputPreview(input: string): string {
  const oneLine = input.replace(/\s+/g, ' ').trim()
  return oneLine.length > 100 ? `${oneLine.slice(0, 100)}…` : oneLine
}

function TruncNote({ chars }: { chars?: number }) {
  return (
    <div className="mt-0.5 text-[11px] italic text-muted-foreground">
      — afgekapt{chars != null ? ` (${chars} chars totaal)` : ''}
    </div>
  )
}

function EventBlock({ event }: { event: LogEvent }): ReactElement {
  switch (event.kind) {
    case 'meta':
      return (
        <div className="flex gap-2 py-0.5 font-mono text-[11px] leading-relaxed">
          <span className="shrink-0 text-muted-foreground/60">{timeOnly(event.ts)}</span>
          <span className={cn('shrink-0 uppercase tracking-wide', META_TAG_STYLES[event.tag])}>
            {event.tag}
          </span>
          <span className="break-all text-muted-foreground">{event.text}</span>
        </div>
      )

    case 'system-init':
      return (
        <div className="my-2 rounded-lg border border-border bg-card p-3 text-xs">
          <div className="mb-1 font-medium text-foreground">Sessie gestart</div>
          <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-muted-foreground sm:grid-cols-3">
            <div>
              <span className="text-foreground/70">model</span> {event.model}
            </div>
            <div>
              <span className="text-foreground/70">permission</span> {event.permissionMode}
            </div>
            <div>
              <span className="text-foreground/70">claude</span> v{event.version || '?'}
            </div>
          </div>
          {event.cwd && (
            <div className="mt-1 break-all font-mono text-[11px] text-muted-foreground">
              cwd: {event.cwd}
            </div>
          )}
          {(event.tools.length > 0 || event.mcpServers.length > 0) && (
            <details className="mt-2">
              <summary className="cursor-pointer text-muted-foreground hover:text-foreground">
                {event.tools.length} tools · {event.mcpServers.length} MCP-server(s)
              </summary>
              <div className="mt-1 font-mono text-[11px] text-muted-foreground">
                {event.mcpServers.length > 0 && <div>mcp: {event.mcpServers.join(', ')}</div>}
                <div className="break-words">{event.tools.join(', ')}</div>
              </div>
            </details>
          )}
        </div>
      )

    case 'assistant-text':
      return (
        <div className="my-1.5 border-l-2 border-blue-300 pl-3 dark:border-blue-700">
          <div className="whitespace-pre-wrap text-sm text-foreground">{event.text}</div>
          {event.truncated && <TruncNote />}
        </div>
      )

    case 'thinking':
      return (
        <details className="my-1 pl-3">
          <summary className="cursor-pointer text-xs italic text-muted-foreground hover:text-foreground">
            thinking…
          </summary>
          <div className="mt-1 whitespace-pre-wrap border-l-2 border-border pl-3 text-xs italic text-muted-foreground">
            {event.text}
            {event.truncated && <TruncNote />}
          </div>
        </details>
      )

    case 'tool-call':
      return (
        <details open className="my-1">
          <summary className="cursor-pointer list-none">
            <span className="inline-flex max-w-full items-center gap-2 rounded-md bg-muted px-2 py-1 text-xs">
              <span className="shrink-0 font-medium text-foreground">▸ {event.name}</span>
              <span className="truncate font-mono text-[11px] text-muted-foreground">
                {inputPreview(event.input)}
              </span>
            </span>
          </summary>
          <pre className="ml-2 mt-1 overflow-x-auto rounded-md border border-border bg-muted/30 p-2 font-mono text-[11px] leading-relaxed">
            {event.input}
          </pre>
          {event.truncated && <TruncNote />}
        </details>
      )

    case 'tool-result':
      return (
        <details className="my-1">
          <summary className="cursor-pointer list-none">
            <span
              className={cn(
                'inline-flex items-center gap-2 rounded-md px-2 py-1 text-xs',
                event.isError
                  ? 'bg-destructive/10 text-destructive'
                  : 'bg-muted text-muted-foreground',
              )}
            >
              <span>{event.isError ? '✕ result (error)' : '◂ result'}</span>
              <span className="text-[11px] opacity-70">{event.fullLength} chars</span>
            </span>
          </summary>
          <pre
            className={cn(
              'ml-2 mt-1 max-h-80 overflow-auto whitespace-pre-wrap break-all rounded-md border p-2 font-mono text-[11px] leading-relaxed',
              event.isError ? 'border-destructive/30 bg-destructive/5' : 'border-border bg-muted/30',
            )}
          >
            {event.body || '(body weggelaten — timeline ingekort)'}
          </pre>
          {event.truncated && <TruncNote chars={event.fullLength} />}
        </details>
      )

    case 'rate-limit':
      return (
        <div className="my-1 text-xs">
          <span className="rounded-md bg-amber-100 px-2 py-0.5 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400">
            rate limit: {event.status}
          </span>
        </div>
      )

    case 'result':
      return (
        <div
          className={cn(
            'my-2 rounded-lg border p-3',
            event.isError
              ? 'border-destructive/30 bg-destructive/10'
              : 'border-green-300 bg-green-50 dark:border-green-800 dark:bg-green-900/20',
          )}
        >
          <div className="flex flex-wrap items-center gap-3 text-xs">
            <span className="font-medium text-foreground">Resultaat: {event.subtype}</span>
            {event.durationMs != null && (
              <span className="text-muted-foreground">{formatDuration(event.durationMs)}</span>
            )}
            {event.numTurns != null && (
              <span className="text-muted-foreground">{event.numTurns} turns</span>
            )}
            {event.totalCostUsd != null && (
              <span className="text-muted-foreground">${event.totalCostUsd.toFixed(2)}</span>
            )}
          </div>
          {event.resultText && (
            <div className="mt-2 whitespace-pre-wrap text-sm text-foreground">
              {event.resultText}
            </div>
          )}
          {event.resultTruncated && <TruncNote />}
        </div>
      )

    case 'raw':
      return (
        <div className="break-all py-0.5 font-mono text-[11px] text-muted-foreground/70">
          {event.text}
        </div>
      )
  }
}

export default function RunLogDetail({ fileName }: { fileName: string }) {
  const [data, setData] = useState<ParsedRunLog | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  const load = useCallback(async () => {
    try {
      const d = await fetchDetail(fileName)
      setData(d)
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'kon log niet laden')
    } finally {
      setLoading(false)
    }
  }, [fileName])

  useEffect(() => {
    setLoading(true)
    setData(null)
    setError(null)
    load()
  }, [load])

  // Keep refreshing while the run is still in progress.
  useEffect(() => {
    if (!data?.inProgress) return
    const id = setInterval(load, 5000)
    return () => clearInterval(id)
  }, [data?.inProgress, load])

  if (loading) {
    return <div className="animate-pulse text-xs text-muted-foreground">log laden…</div>
  }
  if (error) {
    return (
      <div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
        {error}
      </div>
    )
  }
  if (!data) return null

  const { summary, events } = data

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
        <span className="font-mono text-foreground">{summary.fileName}</span>
        {summary.jobId && <span className="font-mono">job {summary.jobId}</span>}
        {summary.model && <span>{summary.model}</span>}
        {summary.permissionMode && <span>{summary.permissionMode}</span>}
        {summary.durationMs != null && <span>{formatDuration(summary.durationMs)}</span>}
        {data.inProgress && (
          <span className="animate-pulse text-amber-600 dark:text-amber-400">● running…</span>
        )}
        {data.responseTruncated && (
          <span className="italic">timeline ingekort (zeer grote log)</span>
        )}
      </div>

      {summary.errorSummary && (
        <div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
          {summary.errorSummary}
        </div>
      )}

      <div className="rounded-lg border border-border bg-background p-3">
        {events.length === 0 ? (
          <div className="text-xs text-muted-foreground">geen events</div>
        ) : (
          events.map((event, i) => <EventBlock key={i} event={event} />)
        )}
      </div>
    </div>
  )
}
