'use client'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { listSandboxes, listTemplates, listEnvironments, createSandbox, cloneSandbox, deleteSandbox, type Sandbox, type Environment } from '@/lib/api'

export default function SandboxesPage() {
  const [sbs, setSbs] = useState<Sandbox[]>([])
  const [templates, setTemplates] = useState<{ id: string; name: string }[]>([])
  const [envs, setEnvs] = useState<Environment[]>([])
  const [error, setError] = useState<string | null>(null)

  const [newName, setNewName] = useState('')
  const [newBranch, setNewBranch] = useState('')
  const [newPort, setNewPort] = useState('')
  const [cloneTemplateId, setCloneTemplateId] = useState('')
  const [cloneName, setCloneName] = useState('')
  const [busy, setBusy] = useState(false)

  async function refresh() {
    try {
      const [s, t, e] = await Promise.all([listSandboxes(), listTemplates(), listEnvironments()])
      setSbs(s)
      setTemplates(t.map((x) => ({ id: x.id, name: x.name })))
      setEnvs(e)
    } catch (err) {
      setError(String(err))
    }
  }
  useEffect(() => { refresh() }, [])

  async function create() {
    if (!newName) return
    setBusy(true)
    setError(null)
    try {
      await createSandbox({
        name: newName,
        gatewayBranch: newBranch || undefined,
        gatewayHostPort: newPort ? Number(newPort) : 0,
      })
      setNewName(''); setNewBranch(''); setNewPort('')
      await refresh()
    } catch (e) {
      setError(String(e))
    } finally {
      setBusy(false)
    }
  }

  async function clone() {
    if (!cloneTemplateId || !cloneName) return
    setBusy(true)
    setError(null)
    try {
      await cloneSandbox(cloneTemplateId, cloneName)
      setCloneName('')
      await refresh()
    } catch (e) {
      setError(String(e))
    } finally {
      setBusy(false)
    }
  }

  async function del(id: string) {
    if (!confirm('Delete this sandbox? Route overrides are dropped but no containers are stopped.')) return
    setBusy(true)
    try {
      await deleteSandbox(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">Sandboxes</h1>
        <p className="text-sm text-muted-foreground">
          A sandbox groups one gateway branch with a set of microservice overrides. Each route can be pointed at the local stand-in or back at OCP.
        </p>
      </div>

      {error && <p className="text-sm text-destructive">{error}</p>}

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>New sandbox</CardTitle>
            <CardDescription>Pick a gateway branch. Add services after creating.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="space-y-1.5">
              <Label>Name</Label>
              <Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="QA-login-error" />
            </div>
            <div className="space-y-1.5">
              <Label>Gateway branch</Label>
              <Input value={newBranch} onChange={(e) => setNewBranch(e.target.value)} placeholder="develop" />
            </div>
            <div className="space-y-1.5">
              <Label>Gateway host port</Label>
              <Input value={newPort} onChange={(e) => setNewPort(e.target.value)} placeholder="8080" />
              <p className="text-xs text-muted-foreground">Port on the gateway VM that the mobile app points at. One live at a time.</p>
            </div>
            <Button onClick={create} disabled={!newName || busy} className="w-full">Create</Button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Clone from template</CardTitle>
            <CardDescription>Materialize a sandbox from a saved template.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="space-y-1.5">
              <Label>Template</Label>
              <Select value={cloneTemplateId} onValueChange={setCloneTemplateId}>
                <SelectTrigger><SelectValue placeholder="Pick a template" /></SelectTrigger>
                <SelectContent>
                  {templates.map((t) => (
                    <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label>New sandbox name</Label>
              <Input value={cloneName} onChange={(e) => setCloneName(e.target.value)} placeholder="QA-login-error" />
            </div>
            <Button onClick={clone} disabled={!cloneTemplateId || !cloneName || busy} className="w-full">Clone</Button>
          </CardContent>
        </Card>
      </div>

      <div className="space-y-2">
        {sbs.length === 0 ? (
          <p className="text-sm text-muted-foreground">No sandboxes yet.</p>
        ) : (
          sbs.map((s) => (
            <Card key={s.id}>
              <CardContent className="flex items-center justify-between p-4">
                <div>
                  <Link href={`/dashboard/sandboxes/${s.id}`} className="font-medium hover:underline">
                    {s.name}
                  </Link>
                  <p className="text-xs text-muted-foreground">
                    Gateway branch: <span className="font-mono">{s.gatewayBranch || '—'}</span>
                    {' · '}
                    Gateway port: <span className="font-mono">{s.gatewayHostPort || '—'}</span>
                    {' · '}
                    Services: <span className="font-mono">{s.services.length}</span>
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Button asChild variant="outline" size="sm"><Link href={`/dashboard/sandboxes/${s.id}`}>Open</Link></Button>
                  <Button onClick={() => del(s.id)} variant="outline" size="sm" disabled={busy}>Delete</Button>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
