import { useEffect, useMemo, useState } from 'react'
import { Button, Card, Col, Row, Space, Statistic, Tabs, Typography, message } from 'antd'
import { systemApi } from '@/lib/api'

export function SystemConfigPage() {
  const [config, setConfig] = useState<Record<string, unknown>>({})
  const [text, setText] = useState('')
  const [loading, setLoading] = useState(false)

  const summary = useMemo(() => {
    const system = (config.system || {}) as Record<string, unknown>
    return {
      addr: system.addr || '-',
      dbType: system['db-type'] || '-',
      routerPrefix: system['router-prefix'] || '/',
      strictAuth: String(system['use-strict-auth'] ?? false),
    }
  }, [config])

  const reloadConfig = async () => {
    setLoading(true)
    try {
      const response = await systemApi.getSystemConfig()
      setConfig(response.data.config)
      setText(JSON.stringify(response.data.config, null, 2))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    reloadConfig()
  }, [])

  const saveConfig = async () => {
    const parsed = JSON.parse(text) as Record<string, unknown>
    await systemApi.setSystemConfig(parsed)
    message.success('配置已保存')
    setConfig(parsed)
  }

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              系统配置
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              当前页以原始 JSON 为主视图，优先保证配置项覆盖完整，不丢字段。
            </Typography.Paragraph>
          </div>
          <Space>
            <Button onClick={reloadConfig} loading={loading}>
              重新加载
            </Button>
            <Button
              onClick={async () => {
                await systemApi.reloadSystem()
                message.success('系统重载命令已发送')
              }}
            >
              重载系统
            </Button>
            <Button type="primary" onClick={saveConfig}>
              保存配置
            </Button>
          </Space>
        </div>
        <Row gutter={16}>
          <Col xs={24} md={6}>
            <Card bordered={false}>
              <Statistic title="服务端口" value={String(summary.addr)} />
            </Card>
          </Col>
          <Col xs={24} md={6}>
            <Card bordered={false}>
              <Statistic title="数据库类型" value={String(summary.dbType)} />
            </Card>
          </Col>
          <Col xs={24} md={6}>
            <Card bordered={false}>
              <Statistic title="路由前缀" value={String(summary.routerPrefix)} />
            </Card>
          </Col>
          <Col xs={24} md={6}>
            <Card bordered={false}>
              <Statistic title="严格权限模式" value={String(summary.strictAuth)} />
            </Card>
          </Col>
        </Row>
      </Card>
      <Card className="glass-panel page-panel" loading={loading}>
        <Tabs
          items={[
            {
              key: 'editor',
              label: 'JSON 编辑器',
              children: (
                <textarea
                  value={text}
                  onChange={(event) => setText(event.target.value)}
                  style={{
                    width: '100%',
                    minHeight: 540,
                    borderRadius: 16,
                    border: '1px solid rgba(16, 37, 66, 0.12)',
                    padding: 16,
                    fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
                    fontSize: 14,
                  }}
                />
              ),
            },
            {
              key: 'preview',
              label: '结构预览',
              children: (
                <pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
                  {JSON.stringify(config, null, 2)}
                </pre>
              ),
            },
          ]}
        />
      </Card>
    </div>
  )
}
