import { PageContainer } from '@ant-design/pro-components';
import { Table, Input, Button, message, Card } from 'antd';
import { useEffect, useState } from 'react';
import { listConfigs, updateConfig } from '@/services/api';

const ConfigsPage: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  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 = [
    { title: '配置名称', dataIndex: 'configName', key: 'configName' },
    { title: '配置键', dataIndex: 'configKey', key: 'configKey' },
    {
      title: '配置值', dataIndex: 'configValue', key: 'configValue',
      render: (v: string, record: any) =>
        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: (_: any, record: any) =>
        editingKey === record.configKey
          ? <>
              <a onClick={() => handleSave(record.configKey)} style={{ marginRight: 8 }}>保存</a>
              <a onClick={() => setEditingKey('')}>取消</a>
            </>
          : <a onClick={() => { setEditingKey(record.configKey); setEditValue(record.configValue); }}>编辑</a>,
    },
  ];

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

export default ConfigsPage;
