'use client'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { listEnvironments, createEnvironment, deleteEnvironment, type Environment } from '@/lib/api'

export default function EnvironmentsPage() {
  const [envs, setEnvs] = useState<Environment[]>([])
  const [error, setError] = useState<string | null>(null)
  const [name, setName] = useState('')
  const [body, setBody] = useState('KEY=value')
  const [busy, setBusy] = useState(false)

  async function refresh() {
    try { setEnvs(await listEnvironments()) } catch (e) { setError(String(e)) }
  }
  useEffect(() => { refresh() }, [])

  async function create() {
    if (!name) return
    const values: Record<string, string> = {}
    for (const line of body.split('\n')) {
      const t = line.trim()
      if (!t || !t.includes('=')) continue
      const i = t.indexOf('=')
      values[t.slice(0, i).trim()] = t.slice(i + 1).trim()
    }
    setBusy(true); setError(null)
    try {
      await createEnvironment(name, values)
      setName('')
      await refresh()
    } catch (e) { setError(String(e)) } finally { setBusy(false) }
  }

  async function del(id: string) {
    if (!confirm('Delete this environment?')) return
    setBusy(true)
    try { await deleteEnvironment(id); await refresh() } catch (e) { setError(String(e)) } finally { setBusy(false) }
  }

  return (
    <div className="container py-8 space-y-6">
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">Environments</h1>
        <p className="text-sm text-muted-foreground">Named sets of env vars. Attach to a sandbox, a service, or the gateway.</p>
      </div>
      {error && <p className="text-sm text-destructive">{error}</p>}
      <Card>
        <CardHeader>
          <CardTitle>New environment</CardTitle>
          <CardDescription>KEY=value per line.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="space-y-1.5">
            <Label>Name</Label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="dev-creds" />
          </div>
          <div className="space-y-1.5">
            <Label>Values</Label>
            <textarea
              className="flex min-h-[120px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm font-mono shadow-sm"
              value={body}
              onChange={(e) => setBody(e.target.value)}
            />
          </div>
          <Button onClick={create} disabled={!name || busy}>Create</Button>
        </CardContent>
      </Card>
      <div className="space-y-2">
        {envs.length === 0 ? (
          <p className="text-sm text-muted-foreground">No environments yet.</p>
        ) : (
          envs.map((e) => (
            <Card key={e.id}>
              <CardContent className="flex items-start justify-between p-4 gap-4">
                <div>
                  <div className="font-medium">{e.name}</div>
                  <pre className="text-xs text-muted-foreground font-mono mt-1 whitespace-pre-wrap">
                    {Object.entries(e.values).map(([k, v]) => `${k}=${v}`).join('\n')}
                  </pre>
                </div>
                <Button variant="outline" size="sm" onClick={() => del(e.id)} disabled={busy}>Delete</Button>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
