import { For, Show } from "solid-js"
import { useTheme } from "@tui/context/theme"
import { getWorkerState, type WorkerInfo } from "@/saeeol/worker"

const STATUS_ICON: Record<string, string> = {
  queued: "□",
  spawning: "◐",
  running: "◐",
  done: "●",
  error: "✕",
  cancelled: "⊘",
}

const STATUS_COLOR: Record<string, string> = {
  queued: "gray",
  spawning: "blue",
  running: "blue",
  done: "green",
  error: "red",
  cancelled: "yellow",
}

export function WorkerCell(props: { worker: WorkerInfo; selected: boolean }) {
  const theme = useTheme()
  const w = () => props.worker
  const icon = () => STATUS_ICON[w().status] ?? "?"
  const color = () => STATUS_COLOR[w().status] ?? "white"
  const bg = () => props.selected ? ((theme as any).base00 ?? "#1a1a2e") : "transparent"

  const desc = () => {
    const d = w().description
    return d.length > 16 ? d.slice(0, 15) + "…" : d
  }

  const tokens = () => {
    const t = w().tokens
    const total = (t.input + t.output + t.reasoning) / 1000
    return total < 1 ? "" : `${total.toFixed(1)}k`
  }

  return (
    <box
      paddingLeft={1}
      paddingRight={1}
      paddingTop={0}
      paddingBottom={0}
      border={props.selected}
      borderStyle={props.selected ? "single" : undefined}
      borderColor={props.selected ? "cyan" : undefined}
      backgroundColor={bg()}
    >
      <text fg={color()}>{icon()} </text>
      <text fg="white">W{w().index + 1}</text>
      <text fg="gray"> @{w().agent}</text>
      {"\n"}
      <text fg="gray">{desc()}</text>
      <Show when={tokens()}>
        <text fg="gray"> {tokens()}</text>
      </Show>
    </box>
  )
}
