import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Table, Input, Button, message, Card, Space } from 'antd';
import { listConfigs, updateConfig } from '@/services/api';
import type { SystemConfig } from '@/types/api';
import type { ColumnsType } from 'antd/es/table';

const ConfigsPage: React.FC = () => {
  const [data, setData] = useState<SystemConfig[]>([]);
  const [loading, setLoading] = useState(false);
  const [editingKey, setEditingKey] = useState('');
  const [editValue, setEditValue] = useState('');

  const fetchData = async () => {
    setLoading(true);
    const res = await listConfigs();
    if (res?.code === 0) setData(res.data?.list || []);
    setLoading(false);
  };

  useEffect(() => { fetchData(); }, []);

  const handleSave = async (key: string) => {
    const res = await updateConfig(key, editValue);
    if (res?.code === 0) {
      message.success('更新成功');
      setEditingKey('');
      fetchData();
    }
  };

  const columns: ColumnsType<SystemConfig> = [
    { title: '配置名称', dataIndex: 'configName', key: 'configName' },
    { title: '配置键', dataIndex: 'configKey', key: 'configKey' },
    {
      title: '配置值',
      dataIndex: 'configValue',
      key: 'configValue',
      render: (v, record) =>
        editingKey === record.configKey
          ? <Input value={editValue} onChange={(e) => setEditValue(e.target.value)} style={{ width: 300 }} />
          : v,
    },
    { title: '分组', dataIndex: 'configGroup', key: 'configGroup' },
    { title: '备注', dataIndex: 'remark', key: 'remark', ellipsis: true },
    {
      title: '操作',
      key: 'action',
      render: (_, record) =>
        editingKey === record.configKey ? (
          <Space>
            <a onClick={() => handleSave(record.configKey)}>保存</a>
            <a onClick={() => setEditingKey('')}>取消</a>
          </Space>
        ) : (
          <a onClick={() => { setEditingKey(record.configKey); setEditValue(record.configValue); }}>编辑</a>
        ),
    },
  ];

  return (
    <PageContainer>
      <Card variant="borderless">
        <Table<SystemConfig>
          columns={columns}
          dataSource={data}
          rowKey="configKey"
          loading={loading}
          pagination={false}
        />
      </Card>
    </PageContainer>
  );
};

export default ConfigsPage;
