import * as React from 'react';
import { Drawer, Button, Tabs, Tag, Space, message } from 'antd';
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';
import './AppCardApiDoc.scss';

const { TabPane } = Tabs;

interface Props {
    open: boolean;
    appId: string;
    onClose: () => void;
}

// 代码块组件
const CodeBlock: React.FC<{ code: string; language?: string }> = ({ code, language = 'bash' }) => {
    const [copied, setCopied] = React.useState(false);

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(code);
            setCopied(true);
            message.success('已复制到剪贴板');
            setTimeout(() => setCopied(false), 2000);
        } catch (err) {
            message.error('复制失败');
        }
    };

    return (
        <div className='code-block'>
            <div className='code-header'>
                <span className='code-language'>{language}</span>
                <Button
                    type='text'
                    size='small'
                    icon={copied ? <CheckOutlined /> : <CopyOutlined />}
                    onClick={handleCopy}
                >
                    {copied ? '已复制' : '复制'}
                </Button>
            </div>
            <pre className='code-content'>
                <code>{code}</code>
            </pre>
        </div>
    );
};

// 参数表格组件
const ParamsTable: React.FC<{ params: { name: string; type: string; required: boolean; description: string }[] }> = ({ params }) => (
    <div className='params-table'>
        <table>
            <thead>
                <tr>
                    <th>参数</th>
                    <th>类型</th>
                    <th>必填</th>
                    <th>说明</th>
                </tr>
            </thead>
            <tbody>
                {params.map((param, index) => (
                    <tr key={index}>
                        <td><code>{param.name}</code></td>
                        <td><span className='param-type'>{param.type}</span></td>
                        <td>
                            {param.required ? (
                                <Tag color='red' style={{ fontSize: 12 }}>必填</Tag>
                            ) : (
                                <Tag color='default' style={{ fontSize: 12 }}>可选</Tag>
                            )}
                        </td>
                        <td>{param.description}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    </div>
);

// 响应示例组件
const ResponseExample: React.FC<{ example: string }> = ({ example }) => (
    <div className='response-example'>
        <pre className='example-content'>
            <code>{example}</code>
        </pre>
    </div>
);

const AppCardApiDoc: React.FC<Props> = ({ open, appId, onClose }) => {
    const baseUrl = window.location.origin;
    const apiKey = localStorage.getItem('api_key_demo') || 'your_api_key_here';

    // 通用问答接口 - 使用 appId
    const chatCompletionCode = `curl -X POST ${baseUrl}/api/v1/chat/completions \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer ${apiKey}" \\
  -d '{
    "app_id": "${appId}",
    "messages": [
      {
        "role": "user",
        "content": "你好"
      }
    ],
    "stream": false
  }'`;

    const chatCompletionPython = `import requests

url = "${baseUrl}/api/v1/chat/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer ${apiKey}"
}

data = {
    "app_id": "${appId}",
    "messages": [
        {
            "role": "user",
            "content": "你好"
        }
    ],
    "stream": False
}

response = requests.post(url, headers=headers, json=data)
print(response.json())`;

    // RAG 问答接口 - 使用 appId
    const ragChatCode = `curl -X POST ${baseUrl}/api/v1/rag/chat \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer ${apiKey}" \\
  -d '{
    "app_id": "${appId}",
    "query": "请问...",
    "top_k": 3,
    "score_threshold": 0.7
  }'`;

    const ragChatPython = `import requests

url = "${baseUrl}/api/v1/rag/chat"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer ${apiKey}"
}

data = {
    "app_id": "${appId}",
    "query": "请问...",
    "top_k": 3,
    "score_threshold": 0.7
}

response = requests.post(url, headers=headers, json=data)
print(response.json())`;

    return (
        <Drawer
            title="API 文档"
            placement="right"
            width={700}
            open={open}
            onClose={onClose}
            className='api-doc-drawer'
        >
            <div className='api-doc-content'>
                {/* 接口说明 */}
                <div className='api-section'>
                    <h3 className='section-title'>接口说明</h3>
                    <div className='section-content'>
                        <p>当前应用 ID：<code className='app-id-badge'>{appId}</code></p>
                        <p>以下接口均需传入此 <code>app_id</code> 参数以调用当前应用。</p>
                        <div className='info-cards'>
                            <div className='info-card'>
                                <div className='card-label'>基础 URL</div>
                                <div className='card-value'><code>{baseUrl}/api/v1</code></div>
                            </div>
                            <div className='info-card'>
                                <div className='card-label'>认证方式</div>
                                <div className='card-value'><code>Bearer Token</code></div>
                            </div>
                        </div>
                    </div>
                </div>

                <Tabs defaultActiveKey="1" className='api-tabs'>
                    {/* 通用问答接口 */}
                    <TabPane tab="通用问答" key="1">
                        <div className='api-item'>
                            <div className='api-header'>
                                <span className='api-method method-post'>POST</span>
                                <span className='api-path'>/api/v1/chat/completions</span>
                            </div>
                            <p className='api-description'>
                                兼容 OpenAI 格式的通用对话接口，支持多轮对话和流式输出。
                            </p>

                            <h4>请求参数</h4>
                            <ParamsTable params={[
                                { name: 'app_id', type: 'string', required: true, description: `当前应用 ID：${appId}` },
                                { name: 'messages', type: 'array', required: true, description: '对话消息列表，包含 role 和 content' },
                                { name: 'stream', type: 'boolean', required: false, description: '是否使用流式输出，默认 false' },
                            ]} />

                            <h4>代码示例</h4>
                            <div style={{ marginTop: 8 }}>
                                <CodeBlock code={chatCompletionCode} language='bash' />
                            </div>
                            <div style={{ marginTop: 8 }}>
                                <CodeBlock code={chatCompletionPython} language='python' />
                            </div>

                            <ResponseExample example={`{
  "id": "chatcmpl-xxxxxxxx",
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "你好！有什么可以帮助你的？"
    }
  }]
}`} />
                        </div>
                    </TabPane>

                    {/* RAG 问答接口 */}
                    <TabPane tab="RAG 问答" key="2">
                        <div className='api-item'>
                            <div className='api-header'>
                                <span className='api-method method-post'>POST</span>
                                <span className='api-path'>/api/v1/rag/chat</span>
                            </div>
                            <p className='api-description'>
                                基于知识库的 RAG 问答接口，结合检索结果生成准确回答。
                            </p>

                            <h4>请求参数</h4>
                            <ParamsTable params={[
                                { name: 'app_id', type: 'string', required: true, description: `当前应用 ID：${appId}` },
                                { name: 'query', type: 'string', required: true, description: '用户问题' },
                                { name: 'top_k', type: 'integer', required: false, description: '返回最相关的 K 条结果，默认 3' },
                                { name: 'score_threshold', type: 'number', required: false, description: '相似度阈值，默认 0.5' },
                            ]} />

                            <h4>代码示例</h4>
                            <div style={{ marginTop: 8 }}>
                                <CodeBlock code={ragChatCode} language='bash' />
                            </div>
                            <div style={{ marginTop: 8 }}>
                                <CodeBlock code={ragChatPython} language='python' />
                            </div>

                            <ResponseExample example={`{
  "id": "rag-chat-xxxxxxxx",
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "根据检索结果..."
    }
  }],
  "retrieved_chunks": [...]
}`} />
                        </div>
                    </TabPane>
                </Tabs>

                {/* 错误码说明 */}
                <div className='api-section'>
                    <h3 className='section-title'>错误码</h3>
                    <div className='section-content'>
                        <ParamsTable params={[
                            { name: '400', type: '', required: false, description: '请求参数错误' },
                            { name: '401', type: '', required: false, description: '未授权，请检查 API Key' },
                            { name: '404', type: '', required: false, description: '应用不存在' },
                            { name: '500', type: '', required: false, description: '服务器内部错误' },
                        ]} />
                    </div>
                </div>
            </div>
        </Drawer>
    );
};

export default AppCardApiDoc;
