import { useState } from 'react'
import type { FormEvent } from 'react'
import { getApiClient, resetApiClient } from '../lib/api-client'
import {
  getRuntimeConfig,
  setRuntimeConfig,
} from '../lib/runtime-config'
import type { RuntimeConfig } from '../lib/runtime-config'
import { reconnectSocket } from '../lib/socket-client'

export default function WorkspacePage() {
  const [form, setForm] = useState<RuntimeConfig>(getRuntimeConfig())
  const [health, setHealth] = useState('')

  async function onSave(e: FormEvent) {
    e.preventDefault()
    setRuntimeConfig(form)
    resetApiClient()
    reconnectSocket()
    setHealth('配置已保存')
  }

  async function checkHealth() {
    try {
      const res = await getApiClient().get('/healthz')
      setHealth(JSON.stringify(res.data))
    } catch {
      setHealth('healthz 访问失败')
    }
  }

  return (
    <section>
      <h2>工作台</h2>
      <form onSubmit={onSave} style={{ display: 'grid', gap: 8, maxWidth: 760 }}>
        <input
          value={form.guildApiBase}
          onChange={(e) => setForm((v) => ({ ...v, guildApiBase: e.target.value }))}
          placeholder="Guild API Base"
        />
        <input
          value={form.guildSocketBase}
          onChange={(e) => setForm((v) => ({ ...v, guildSocketBase: e.target.value }))}
          placeholder="Guild Socket Base"
        />
        <input
          value={form.apiKey}
          onChange={(e) => setForm((v) => ({ ...v, apiKey: e.target.value }))}
          placeholder="API Key"
        />
        <div style={{ display: 'flex', gap: 8 }}>
          <button type="submit">保存配置</button>
          <button type="button" onClick={checkHealth}>
            测试 healthz
          </button>
        </div>
      </form>
      <p>{health}</p>
    </section>
  )
}
