'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 { listTemplates, createTemplate, deleteTemplate, type Template } from '@/lib/api'

export default function TemplatesPage() {
  const [ts, setTs] = useState<Template[]>([])
  const [error, setError] = useState<string | null>(null)
  const [name, setName] = useState('')
  const [branch, setBranch] = useState('')
  const [busy, setBusy] = useState(false)

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

  async function create() {
    if (!name) return
    setBusy(true); setError(null)
    try {
      await createTemplate({ name, gatewayBranch: branch, services: [] })
      setName(''); setBranch('')
      await refresh()
    } catch (e) { setError(String(e)) } finally { setBusy(false) }
  }

  async function del(id: string) {
    if (!confirm('Delete this template?')) return
    setBusy(true)
    try { await deleteTemplate(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">Templates</h1>
        <p className="text-sm text-muted-foreground">
          A template is a saved set of (gateway branch, services). Clone it into a sandbox from the Sandboxes page.
        </p>
      </div>
      {error && <p className="text-sm text-destructive">{error}</p>}
      <Card>
        <CardHeader>
          <CardTitle>New template</CardTitle>
          <CardDescription>Add services after creating.</CardDescription>
        </CardHeader>
        <CardContent className="grid gap-3 md:grid-cols-3">
          <div className="space-y-1.5">
            <Label>Name</Label>
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="ACCOUNT-TESTING" />
          </div>
          <div className="space-y-1.5">
            <Label>Gateway branch</Label>
            <Input value={branch} onChange={(e) => setBranch(e.target.value)} placeholder="develop" />
          </div>
          <div className="flex items-end">
            <Button onClick={create} disabled={!name || busy} className="w-full">Create</Button>
          </div>
        </CardContent>
      </Card>
      <div className="space-y-2">
        {ts.length === 0 ? (
          <p className="text-sm text-muted-foreground">No templates yet.</p>
        ) : (
          ts.map((t) => (
            <Card key={t.id}>
              <CardContent className="flex items-center justify-between p-4">
                <div>
                  <div className="font-medium">{t.name}</div>
                  <p className="text-xs text-muted-foreground">
                    Gateway: <span className="font-mono">{t.gatewayBranch || '—'}</span> · Services: <span className="font-mono">{t.services.length}</span>
                  </p>
                </div>
                <Button variant="outline" size="sm" onClick={() => del(t.id)} disabled={busy}>Delete</Button>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
