/**
 * KRA - MCP Tools模板
 * 对应 GVA: view/systemTools/autoCode/mcp.vue
 */
import React from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Form, Input, Button, Table, Select, Checkbox, message } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { mcp } from '@/services/kratos/autoCode';

interface ParamItem {
  key: string;
  name: string;
  description: string;
  type: string;
  default?: string;
  required: boolean;
}

interface ResponseItem {
  key: string;
  type: string;
}

const MCP: React.FC = () => {
  const [form] = Form.useForm();
  const [params, setParams] = React.useState<ParamItem[]>([]);
  const [response, setResponse] = React.useState<ResponseItem[]>([]);

  const addParam = () => {
    setParams([...params, {
      key: Date.now().toString(),
      name: '',
      description: '',
      type: 'string',
      default: '',
      required: false,
    }]);
  };

  const removeParam = (key: string) => {
    setParams(params.filter(p => p.key !== key));
  };

  const updateParam = (key: string, field: string, value: any) => {
    setParams(params.map(p => p.key === key ? { ...p, [field]: value } : p));
  };

  const addResponse = () => {
    setResponse([...response, { key: Date.now().toString(), type: 'text' }]);
  };

  const removeResponse = (key: string) => {
    setResponse(response.filter(r => r.key !== key));
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 验证参数
      for (const p of params) {
        if (!p.name || !p.description || !p.type) {
          message.error('请完善所有参数信息');
          return;
        }
      }
      
      // 验证返回参数
      for (const r of response) {
        if (!r.type) {
          message.error('请完善所有返回参数类型');
          return;
        }
      }

      const res = await mcp({
        ...values,
        params: params.map(({ key, ...rest }) => rest),
        response: response.map(({ key, ...rest }) => rest),
      });
      
      if (res.code === 0) {
        message.success(res.msg || '生成成功');
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  const paramColumns = [
    {
      title: '参数名',
      dataIndex: 'name',
      width: 120,
      render: (_: any, record: ParamItem) => (
        <Input
          value={record.name}
          placeholder="参数名"
          onChange={(e) => updateParam(record.key, 'name', e.target.value)}
        />
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      render: (_: any, record: ParamItem) => (
        <Input
          value={record.description}
          placeholder="描述"
          onChange={(e) => updateParam(record.key, 'description', e.target.value)}
        />
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 120,
      render: (_: any, record: ParamItem) => (
        <Select
          value={record.type}
          style={{ width: '100%' }}
          onChange={(value) => updateParam(record.key, 'type', value)}
        >
          <Select.Option value="string">string</Select.Option>
          <Select.Option value="number">number</Select.Option>
          <Select.Option value="boolean">boolean</Select.Option>
          <Select.Option value="object">object</Select.Option>
          <Select.Option value="array">array</Select.Option>
        </Select>
      ),
    },
    {
      title: '默认值',
      dataIndex: 'default',
      width: 150,
      render: (_: any, record: ParamItem) => (
        <Input
          value={record.default}
          disabled={record.type === 'object'}
          onChange={(e) => updateParam(record.key, 'default', e.target.value)}
        />
      ),
    },
    {
      title: '必填',
      dataIndex: 'required',
      width: 80,
      render: (_: any, record: ParamItem) => (
        <Checkbox
          checked={record.required}
          onChange={(e) => updateParam(record.key, 'required', e.target.checked)}
        />
      ),
    },
    {
      title: '操作',
      width: 80,
      render: (_: any, record: ParamItem) => (
        <Button type="link" danger onClick={() => removeParam(record.key)}>
          删除
        </Button>
      ),
    },
  ];

  const responseColumns = [
    {
      title: '类型',
      dataIndex: 'type',
      render: (_: any, record: ResponseItem) => (
        <Select
          value={record.type}
          style={{ width: 200 }}
          onChange={(value) => {
            setResponse(response.map(r => r.key === record.key ? { ...r, type: value } : r));
          }}
        >
          <Select.Option value="text">text</Select.Option>
          <Select.Option value="image">image</Select.Option>
        </Select>
      ),
    },
    {
      title: '操作',
      width: 80,
      render: (_: any, record: ResponseItem) => (
        <Button type="link" danger onClick={() => removeResponse(record.key)}>
          删除
        </Button>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <Form form={form} layout="vertical">
          <Form.Item
            label="工具名称"
            name="name"
            rules={[{ required: true, message: '请输入工具名称' }]}
          >
            <Input placeholder="例:CurrentTime" />
          </Form.Item>
          
          <Form.Item
            label="工具描述"
            name="description"
            rules={[{ required: true, message: '请输入工具描述' }]}
          >
            <Input.TextArea placeholder="请输入工具描述" />
          </Form.Item>

          <Form.Item label="参数列表">
            <Table
              columns={paramColumns}
              dataSource={params}
              rowKey="key"
              pagination={false}
              size="small"
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={addParam}
              style={{ marginTop: 10 }}
            >
              添加参数
            </Button>
          </Form.Item>

          <Form.Item label="返回参数">
            <Table
              columns={responseColumns}
              dataSource={response}
              rowKey="key"
              pagination={false}
              size="small"
            />
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={addResponse}
              style={{ marginTop: 10 }}
            >
              添加返回参数
            </Button>
          </Form.Item>

          <Form.Item>
            <div style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={handleSubmit}>
                生成
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default MCP;
