'use client'
import { useEffect, useState } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { listDeployments, listSandboxes, type Deployment, type Sandbox } from '@/lib/api'

export default function HistoryPage() {
  const [deps, setDeps] = useState<Deployment[]>([])
  const [sbs, setSbs] = useState<Sandbox[]>([])
  const [filter, setFilter] = useState('')
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    listSandboxes().then(setSbs).catch((e) => setError(String(e)))
    refresh('')
  }, [])
  function refresh(sandboxID: string) {
    listDeployments(sandboxID || undefined)
      .then(setDeps)
      .catch((e) => setError(String(e)))
  }

  function shortState(d: Deployment) {
    return d.state
  }

  return (
    <div className="container py-8 space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold tracking-tight">History</h1>
        <div className="flex items-center gap-2 text-sm">
          <label>Sandbox</label>
          <select
            className="h-9 rounded-md border border-input bg-background px-3 text-sm"
            value={filter}
            onChange={(e) => { setFilter(e.target.value); refresh(e.target.value) }}
          >
            <option value="">All</option>
            {sbs.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </div>
      </div>
      {error && <p className="text-sm text-destructive">{error}</p>}
      <div className="space-y-2">
        {deps.length === 0 ? (
          <p className="text-sm text-muted-foreground">No deployments yet.</p>
        ) : (
          deps.map((d) => (
            <Card key={d.id}>
              <CardContent className="flex items-center justify-between p-3">
                <div>
                  <div className="font-mono text-xs text-muted-foreground">{d.id}</div>
                  <div className="text-sm">
                    <span className="font-medium">{d.repository}</span> · <span className="font-mono">{d.branch}</span>
                    {d.sandboxId && <span className="text-muted-foreground"> · {sbs.find((x) => x.id === d.sandboxId)?.name ?? d.sandboxId}</span>}
                  </div>
                </div>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  {d.hostPort ? <Badge variant="outline">:{d.hostPort}</Badge> : null}
                  <Badge variant={stateVariant(shortState(d))}>{shortState(d)}</Badge>
                  <span>{new Date(d.startedAt).toLocaleString()}</span>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}

function stateVariant(s: string) {
  switch (s) {
    case 'RUNNING': return 'success'
    case 'FAILED': return 'destructive'
    case 'STOPPED': return 'warning'
    default: return 'secondary'
  }
}
