'use client'

import { Fragment, useCallback, useEffect, useState } from 'react'
import type { RunLogSummary, RunStatus } from '@/lib/parse-worker-log'
import { cn, formatDuration, relativeTime } from '@/lib/utils'
import RunLogDetail from './run-log-detail'

const LIMIT_OPTIONS = [10, 25, 50, 100]
const COLUMN_COUNT = 7

const STATUS_STYLES: Record<RunStatus, { badge: string; dot: string }> = {
  idle: {
    badge: 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400',
    dot: 'bg-zinc-400 dark:bg-zinc-500',
  },
  running: {
    badge: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
    dot: 'bg-amber-500 dark:bg-amber-400',
  },
  success: {
    badge: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    dot: 'bg-green-500 dark:bg-green-400',
  },
  error: {
    badge: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
    dot: 'bg-red-500 dark:bg-red-400',
  },
  'token-expired': {
    badge: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
    dot: 'bg-red-500 dark:bg-red-400',
  },
  unknown: {
    badge: 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400',
    dot: 'bg-zinc-400 dark:bg-zinc-500',
  },
}

export function StatusBadge({ status }: { status: RunStatus }) {
  const s = STATUS_STYLES[status]
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium',
        s.badge,
      )}
    >
      <span className={cn('size-1.5 rounded-full', s.dot)} />
      {status}
    </span>
  )
}

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

type Props = {
  initialLogs: RunLogSummary[]
  initialError: string | null
}

export default function WorkerLogsView({ initialLogs, initialError }: Props) {
  const [logs, setLogs] = useState<RunLogSummary[]>(initialLogs)
  const [limit, setLimit] = useState(10)
  const [selected, setSelected] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(initialError)
  const [refreshing, setRefreshing] = useState(false)
  const [lastUpdated, setLastUpdated] = useState<Date>(new Date())

  const refresh = useCallback(async () => {
    setRefreshing(true)
    try {
      const data = await fetchLogs(limit)
      setLogs(data)
      setError(null)
      setLastUpdated(new Date())
    } catch (err) {
      setError(err instanceof Error ? err.message : 'refresh failed')
    } finally {
      setRefreshing(false)
    }
  }, [limit])

  useEffect(() => {
    refresh()
    const id = setInterval(refresh, 10000)
    return () => clearInterval(id)
  }, [refresh])

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="text-xs text-muted-foreground">toon</span>
          {LIMIT_OPTIONS.map((opt) => (
            <button
              key={opt}
              onClick={() => setLimit(opt)}
              className={cn(
                'rounded-md border px-2 py-1 text-xs transition-colors',
                limit === opt
                  ? 'border-foreground/30 bg-muted font-medium text-foreground'
                  : 'border-border text-muted-foreground hover:bg-muted/50',
              )}
            >
              {opt}
            </button>
          ))}
          {refreshing && (
            <span className="text-xs text-muted-foreground animate-pulse">refreshing…</span>
          )}
        </div>
        <span className="text-xs text-muted-foreground">
          updated {lastUpdated.toLocaleTimeString()} · auto-refreshes every 10s
        </span>
      </div>

      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {error}
        </div>
      )}

      <div className="overflow-x-auto rounded-lg border border-border">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/50">
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Started</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Status</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Job</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Model</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Turns</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Duration</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Cost</th>
            </tr>
          </thead>
          <tbody>
            {logs.length === 0 && !error ? (
              <tr>
                <td colSpan={COLUMN_COUNT} className="px-4 py-8 text-center text-muted-foreground">
                  No worker runs found
                </td>
              </tr>
            ) : (
              logs.map((log) => {
                const isSelected = selected === log.fileName
                return (
                  <Fragment key={log.fileName}>
                    <tr
                      onClick={() => setSelected(isSelected ? null : log.fileName)}
                      title={log.errorSummary ?? undefined}
                      className={cn(
                        'cursor-pointer border-b border-border transition-colors',
                        isSelected ? 'bg-muted/50' : 'hover:bg-muted/30',
                      )}
                    >
                      <td className="px-4 py-3 text-xs">
                        {log.startedAt ? (
                          <span title={new Date(log.startedAt).toLocaleString()}>
                            {relativeTime(new Date(log.startedAt))}
                          </span>
                        ) : (
                          <span className="font-mono">{log.runId}</span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <StatusBadge status={log.status} />
                      </td>
                      <td className="px-4 py-3 font-mono text-xs text-muted-foreground">
                        {log.jobId ? `…${log.jobId.slice(-8)}` : '—'}
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground">{log.model ?? '—'}</td>
                      <td className="px-4 py-3 text-xs text-muted-foreground">
                        {log.numTurns ?? '—'}
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground">
                        {log.durationMs != null ? formatDuration(log.durationMs) : '—'}
                      </td>
                      <td className="px-4 py-3 text-xs text-muted-foreground">
                        {log.totalCostUsd != null ? `$${log.totalCostUsd.toFixed(2)}` : '—'}
                      </td>
                    </tr>
                    {isSelected && (
                      <tr className="border-b border-border bg-muted/20">
                        <td colSpan={COLUMN_COUNT} className="px-4 py-4">
                          <RunLogDetail fileName={log.fileName} />
                        </td>
                      </tr>
                    )}
                  </Fragment>
                )
              })
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
