import { useEffect, useRef } from 'react'
import { Loader2, Terminal } from 'lucide-react'
import type { Agent, TerminalLine } from '../../types'
import { getAgentMeta } from '../../lib/agentMeta'
import { cn } from '../../lib/utils'
import { subTabIdle } from '../../lib/tabActive'

type Props = {
  agent: Agent
  lines: TerminalLine[]
  busy: boolean
  onSendPrompt: (message: string, agentId?: string) => void
  compact?: boolean
}

const LEVEL: Record<string, string> = {
  info: 'text-foreground-muted',
  ok: 'text-success',
  warn: 'text-warning',
  err: 'text-danger',
  cmd: 'text-docker',
  llm: 'text-violet-400',
  fetch: 'text-cyan-400',
  probe: 'text-amber-300',
}

export function AgentWorkbench({ agent, lines, busy, onSendPrompt, compact }: Props) {
  const meta = getAgentMeta(agent.id)
  const Icon = meta.icon
  const bottomRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [lines, busy])

  return (
    <div className="flex h-full min-h-0 flex-col overflow-hidden">
      <header className={cn('flex shrink-0 items-center gap-2 border-b border-border/60 px-2', compact ? 'py-1' : 'py-3')}>
        <span
          className={cn('flex shrink-0 items-center justify-center rounded-lg border border-border/80 bg-surface-overlay', compact ? 'h-7 w-7' : 'h-10 w-10')}
          style={{ color: meta.accent, boxShadow: compact ? undefined : `0 0 24px ${meta.accent}33` }}
        >
          <Icon className={compact ? 'h-3.5 w-3.5' : 'h-5 w-5'} />
        </span>
        <div className="min-w-0 flex-1">
          <h3 className={cn('truncate font-bold text-foreground', compact ? 'text-xs' : 'text-sm')}>{agent.name}</h3>
          {!compact && <p className="text-[10px] text-docker">{meta.domain} · {agent.zone}</p>}
        </div>
        <div className="flex shrink-0 items-center gap-1.5">
          {busy && <Loader2 className="h-3 w-3 animate-spin text-success" />}
          <span className="flex items-center gap-1 rounded border border-emerald-500/40 bg-emerald-500/10 px-1.5 py-0.5 text-[9px] text-emerald-300">
            <Terminal className="h-3 w-3" /> Terminal
          </span>
        </div>
      </header>

      {!compact && (
        <div className="flex shrink-0 flex-wrap gap-1 border-b border-border/40 px-2 py-1">
          {(agent.suggested_prompts || []).slice(0, 4).map((prompt) => (
            <button
              key={prompt}
              type="button"
              onClick={() => onSendPrompt(prompt, agent.id)}
              className={cn('rounded border border-border/60 px-1.5 py-0.5 text-[9px] text-foreground-muted hover:border-docker/40 hover:text-docker', subTabIdle)}
            >
              {prompt}
            </button>
          ))}
        </div>
      )}

      <div className={cn('scrollbar-thin min-h-0 flex-1 overflow-y-auto font-mono leading-relaxed', compact ? 'px-2 py-1 text-[10px]' : 'px-3 py-2 text-[11px]')}>
        {lines.length === 0 && (
          <p className="py-2 text-center text-foreground-faint">Agent terminal ready</p>
        )}
        {lines.map((line) => (
          <div key={line.id} className={LEVEL[line.level] || 'text-foreground-muted'}>
            <span className="text-foreground-faint/50">
              {line.ts ? new Date(line.ts).toLocaleTimeString('en-US', { hour12: false }) : ''}
            </span>{' '}
            <span className="text-docker/70">[{line.phase}]</span> {line.text}
          </div>
        ))}
        {busy && <span className="text-docker animate-pulse">█</span>}
        <div ref={bottomRef} />
      </div>
    </div>
  )
}
