'use client'

import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { type Container, parseDockerPs } from '@/lib/parse-docker'

async function fetchContainers(): Promise<Container[]> {
  const res = await fetch('/api/agent/exec', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ command_key: 'docker_ps' }),
  })

  if (!res.ok) {
    const text = await res.text()
    throw new Error(`agent ${res.status}: ${text}`)
  }

  const reader = res.body?.getReader()
  if (!reader) throw new Error('no response body')

  const decoder = new TextDecoder()
  let buffer = ''
  let output = ''

  while (true) {
    const { done, value } = await reader.read()
    if (done) break

    buffer += decoder.decode(value, { stream: true })
    const lines = buffer.split('\n')
    buffer = lines.pop() ?? ''

    for (const line of lines) {
      if (line.startsWith('data:')) {
        try {
          const parsed = JSON.parse(line.slice(5).trim()) as { data?: string }
          if (parsed.data !== undefined) output += parsed.data
        } catch {
          // ignore malformed
        }
      }
    }
  }

  return parseDockerPs(output)
}

function statusBadge(status: string) {
  const up = status.toLowerCase().startsWith('up')
  return (
    <span
      className={
        'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium ' +
        (up
          ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
          : 'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400')
      }
    >
      <span
        className={
          'size-1.5 rounded-full ' +
          (up ? 'bg-green-500 dark:bg-green-400' : 'bg-zinc-400 dark:bg-zinc-500')
        }
      />
      {status}
    </span>
  )
}

type Props = {
  initialContainers: Container[]
  initialError: string | null
}

export default function DockerTable({ initialContainers, initialError }: Props) {
  const [containers, setContainers] = useState<Container[]>(initialContainers)
  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 fetchContainers()
      setContainers(data)
      setError(null)
      setLastUpdated(new Date())
    } catch (err) {
      setError(err instanceof Error ? err.message : 'refresh failed')
    } finally {
      setRefreshing(false)
    }
  }, [])

  useEffect(() => {
    const id = setInterval(refresh, 5000)
    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-sm text-muted-foreground">
            {containers.length} container{containers.length !== 1 ? 's' : ''}
          </span>
          {refreshing && (
            <span className="text-xs text-muted-foreground animate-pulse">refreshing…</span>
          )}
        </div>
        <span className="text-xs text-muted-foreground">
          updated {lastUpdated.toLocaleTimeString()}
        </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">Name</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Image</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">Ports</th>
              <th className="px-4 py-3 text-left font-medium text-muted-foreground">Uptime</th>
            </tr>
          </thead>
          <tbody>
            {containers.length === 0 && !error ? (
              <tr>
                <td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">
                  No containers running
                </td>
              </tr>
            ) : (
              containers.map((c) => (
                <tr
                  key={c.id}
                  className="border-b border-border last:border-0 hover:bg-muted/30 transition-colors"
                >
                  <td className="px-4 py-3 font-mono text-xs">
                    <Link
                      href={`/docker/${encodeURIComponent(c.name)}`}
                      className="font-medium text-foreground hover:underline"
                    >
                      {c.name}
                    </Link>
                  </td>
                  <td className="px-4 py-3 font-mono text-xs text-muted-foreground">{c.image}</td>
                  <td className="px-4 py-3">{statusBadge(c.status)}</td>
                  <td className="px-4 py-3 font-mono text-xs text-muted-foreground">
                    {c.ports || '—'}
                  </td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">{c.created}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
