import { Show } from "solid-js"
import { getWorkerState, type WorkerInfo } from "@/saeeol/worker"

const STATUS_LABEL: Record<string, string> = {
  queued: "대기 중",
  spawning: "시작 중",
  running: "실행 중",
  done: "완료",
  error: "에러",
  cancelled: "취소됨",
}

export function WorkerDetail() {
  const state = getWorkerState

  const selected = () => {
    const id = state().selectedID
    if (!id) return null
    return state().workers[id] ?? null
  }

  const progress = (w: WorkerInfo) =>
    w.progress != null ? `[${"█".repeat(Math.floor(w.progress / 5))}${"░".repeat(20 - Math.floor(w.progress / 5))}] ${w.progress}%` : ""

  const elapsed = (w: WorkerInfo) => {
    const ms = (w.completed ?? Date.now()) - w.spawned
    return `${(ms / 1000).toFixed(0)}s`
  }

  const totalTokens = (w: WorkerInfo) => {
    const t = w.tokens
    return ((t.input + t.output + t.reasoning) / 1000).toFixed(1) + "k"
  }

  return (
    <Show when={selected()} fallback={<text fg="gray">워커를 선택하세요 (↑↓)</text>}>
      {(w) => (
        <box paddingLeft={1} paddingTop={0} paddingBottom={0} paddingRight={1}>
          <text fg="cyan"><b>Worker #{w().index + 1} </b></text>
          <text fg="gray">@{w().agent}</text>
          {"\n"}
          <text fg="white">상태: </text>
          <text fg={w().status === "error" ? "red" : w().status === "done" ? "green" : "blue"}>
            <b>{STATUS_LABEL[w().status] ?? w().status}</b>
          </text>
          <text fg="gray"> {elapsed(w())}</text>
          {"\n"}
          <text fg="white">작업: </text>
          <text>{w().description}</text>
          {"\n"}
          <text fg="white">토큰: </text>
          <text fg="gray">{totalTokens(w())}</text>
          <text fg="white"> 비용: </text>
          <text fg="gray">${w().cost.toFixed(4)}</text>
          {"\n"}
          <Show when={progress(w())}>
            <text fg="cyan">{progress(w())}</text>
            {"\n"}
          </Show>
          <Show when={w().error}>
            <text fg="red">{w().error}</text>
            {"\n"}
          </Show>
          <Show when={w().output}>
            <text fg="gray">{(w().output ?? "").slice(0, 500)}</text>
          </Show>
          {"\n"}
          <text fg="gray">ESC:그리드 | ↑↓:이동 | Ctrl+C:취소</text>
        </box>
      )}
    </Show>
  )
}
