import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { ApiError } from '../api/client'
import { Card, PageTitle } from '../components/ui'
import type { JobTemplateData } from '../types/api'

export function JobTemplatesPage() {
  const [templates, setTemplates] = useState<JobTemplateData[]>([])
  const [error, setError] = useState('')

  useEffect(() => {
    api
      .get<{ list: JobTemplateData[] }>('/api/v1/job/templates', { auth: true })
      .then((d) => setTemplates(d.list))
      .catch((e: ApiError) => setError(e.message))
  }, [])

  return (
    <div>
      <PageTitle title="Job 模板" subtitle="GET /api/v1/job/templates" />
      {error ? <p className="text-rose-600">{error}</p> : null}
      <div className="grid gap-4">
        {templates.map((t) => (
          <Card key={t.type}>
            <div className="flex items-start justify-between gap-4">
              <div>
                <h2 className="font-semibold">{t.name}</h2>
                <p className="text-sm text-ink-secondary">{t.type} · v{t.version}</p>
                <p className="mt-2 text-sm">{t.description || '—'}</p>
              </div>
              <span className={`rounded-[var(--radius-pill)] px-3 py-1 text-xs font-medium ${t.enabled ? 'bg-brand-soft text-brand' : 'bg-accent-soft text-muted'}`}>
                {t.enabled ? 'enabled' : 'disabled'}
              </span>
            </div>
            <pre className="mt-4 overflow-auto rounded-[var(--radius-md)] bg-surface-muted p-4 text-xs">
              {JSON.stringify(t.steps, null, 2)}
            </pre>
          </Card>
        ))}
      </div>
    </div>
  )
}