import { useEffect, useState } from 'react'
import { promptsApi } from '@/services/api'

export default function PromptTemplatesPanel() {
  const [list, setList] = useState<any[]>([])
  const [active, setActive] = useState<any | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let mounted = true
    ;(async () => {
      try {
        setLoading(true)
        const rows = await promptsApi.list()
        if (mounted) setList(rows)
        if (rows?.[0]) setActive(await promptsApi.get(rows[0].name))
      } catch (e: any) {
        setError(e?.message || 'Failed to load prompt templates')
      } finally {
        setLoading(false)
      }
    })()
    return () => { mounted = false }
  }, [])

  const load = async (name: string) => {
    try { setActive(await promptsApi.get(name)) } catch {}
  }

  return (
    <div className="card" style={{ display: 'grid', gap: 12 }}>
      <div className="title">Prompt Templates</div>
      {loading && <div className="text-gray-400">Loading…</div>}
      {error && <div className="text-red-500">{error}</div>}
      {!loading && !error && (
        <div style={{ display: 'grid', gap: 12, gridTemplateColumns: '1fr 2fr' }}>
          <div className="card">
            <div className="text-gray-300 font-semibold mb-2">Templates</div>
            <ul className="space-y-1">
              {list.map(t => (
                <li key={t.name}>
                  <button className="btn bg-dark-bg w-full text-left" onClick={() => load(t.name)}>
                    <div className="font-medium">{t.name}</div>
                    <div className="text-gray-400 text-xs">{t.description}</div>
                  </button>
                </li>
              ))}
            </ul>
          </div>
          <div className="card">
            {active ? (
              <div>
                <div className="text-gray-300 font-semibold">{active.name}</div>
                <div className="text-gray-400 text-sm mb-2">Vars: {active.variables?.join(', ') || '-'}</div>
                <pre className="whitespace-pre-wrap text-gray-100 text-sm bg-dark-bg p-3 rounded border border-dark-border">{active.body}</pre>
              </div>
            ) : (
              <div className="text-gray-400">Select a template</div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}