import { useEffect, useState } from 'react';
import { Drawer, Tabs, Button, List, Space, Tag, App as AntApp, Empty, Modal, Form, Input, Spin } from 'antd';
import { McpAPI, McpStatus } from '../api';

interface Props {
  agentId: string;
  open: boolean;
  onClose: () => void;
  /** 当用户选中要"使用"某个 Resource 或 Prompt 时，回调把内容塞回输入框 */
  onUse: (text: string) => void;
}

export default function McpResourcesDrawer({ agentId, open, onClose, onUse }: Props) {
  const { message } = AntApp.useApp();
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<McpStatus[]>([]);
  const [contentModal, setContentModal] = useState<{ title: string; content: string } | null>(null);
  const [promptModal, setPromptModal] = useState<{ server: McpStatus; prompt: any } | null>(null);
  const [promptArgs, setPromptArgs] = useState<Record<string, any>>({});

  const load = async () => {
    setLoading(true);
    try {
      const s = await McpAPI.status(agentId);
      setStatus(s);
    } catch (e: any) {
      message.error('加载失败：' + (e?.message ?? e));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, agentId]);

  const handleReadResource = async (serverId: string, uri: string, name: string) => {
    try {
      const r = await McpAPI.readResource(agentId, serverId, uri);
      // 把 contents 拼成 markdown 文本
      const text = (r.contents ?? [])
        .map((c: any) => {
          if (c.text) return c.text;
          if (c.blob) return `[binary blob: ${c.mimeType}, ${c.blob.length} bytes]`;
          return '';
        })
        .filter(Boolean)
        .join('\n\n');
      setContentModal({ title: name || uri, content: text || '(空)' });
    } catch (e: any) {
      message.error('读取失败：' + (e?.message ?? e));
    }
  };

  const handleGetPrompt = async () => {
    if (!promptModal) return;
    try {
      const r = await McpAPI.getPrompt(agentId, promptModal.server.id, promptModal.prompt.name, promptArgs);
      // prompt 的 messages 转成可用文本
      const text = (r.messages ?? [])
        .map((m: any) => {
          if (typeof m.content === 'string') return m.content;
          if (m.content?.text) return m.content.text;
          if (Array.isArray(m.content)) return m.content.map((c: any) => c.text || '').filter(Boolean).join('\n');
          return '';
        })
        .filter(Boolean)
        .join('\n\n');
      onUse(text);
      message.success('已填充到输入框');
      setPromptModal(null);
      setPromptArgs({});
      onClose();
    } catch (e: any) {
      message.error('获取失败：' + (e?.message ?? e));
    }
  };

  return (
    <>
      <Drawer
        open={open}
        onClose={onClose}
        title="🔌 MCP 资源 & 提示词"
        width={680}
        extra={
          <Button onClick={load} loading={loading}>
            🔄 刷新
          </Button>
        }
      >
        {loading ? (
          <Spin />
        ) : status.length === 0 ? (
          <Empty description="此智能体未配置 MCP Server" />
        ) : (
          <Tabs
            items={status.map((srv) => ({
              key: srv.id,
              label: (
                <Space>
                  <span>{srv.name}</span>
                  {srv.error ? (
                    <Tag color="error">连接失败</Tag>
                  ) : (
                    <>
                      <Tag>{srv.resourceCount} 资源</Tag>
                      <Tag>{srv.promptCount} 提示词</Tag>
                    </>
                  )}
                </Space>
              ),
              children: srv.error ? (
                <Empty description={`连接失败：${srv.error}`} />
              ) : (
                <Tabs
                  size="small"
                  items={[
                    {
                      key: 'res',
                      label: `📄 Resources (${srv.resourceCount})`,
                      children: srv.resources.length === 0 ? (
                        <Empty description="该 Server 不提供 Resources" />
                      ) : (
                        <List
                          dataSource={srv.resources}
                          renderItem={(r) => (
                            <List.Item
                              actions={[
                                <Button
                                  key="read"
                                  size="small"
                                  onClick={() => handleReadResource(srv.id, r.uri, r.name || r.uri)}
                                >
                                  读取
                                </Button>,
                                <Button
                                  key="use"
                                  type="primary"
                                  size="small"
                                  onClick={async () => {
                                    const data = await McpAPI.readResource(agentId, srv.id, r.uri);
                                    const text = (data.contents ?? [])
                                      .map((c: any) => c.text || '')
                                      .filter(Boolean)
                                      .join('\n\n');
                                    onUse(`请基于以下资料回答：\n\n---\n${text}\n---\n\n`);
                                    onClose();
                                  }}
                                >
                                  使用
                                </Button>
                              ]}
                            >
                              <List.Item.Meta
                                title={
                                  <Space>
                                    <span>{r.name || r.uri.split('/').pop()}</span>
                                    {r.mimeType && <Tag color="geekblue">{r.mimeType}</Tag>}
                                  </Space>
                                }
                                description={
                                  <div>
                                    <code style={{ fontSize: 11 }}>{r.uri}</code>
                                    {r.description && <div style={{ marginTop: 4 }}>{r.description}</div>}
                                  </div>
                                }
                              />
                            </List.Item>
                          )}
                        />
                      )
                    },
                    {
                      key: 'pr',
                      label: `💡 Prompts (${srv.promptCount})`,
                      children: srv.prompts.length === 0 ? (
                        <Empty description="该 Server 不提供 Prompts" />
                      ) : (
                        <List
                          dataSource={srv.prompts}
                          renderItem={(p) => (
                            <List.Item
                              actions={[
                                <Button
                                  key="use"
                                  type="primary"
                                  size="small"
                                  onClick={() => {
                                    setPromptModal({ server: srv, prompt: p });
                                    setPromptArgs({});
                                  }}
                                >
                                  使用
                                </Button>
                              ]}
                            >
                              <List.Item.Meta
                                title={p.name}
                                description={
                                  <div>
                                    {p.description}
                                    {p.arguments && p.arguments.length > 0 && (
                                      <div style={{ marginTop: 4 }}>
                                        <Space size={4} wrap>
                                          {p.arguments.map((a: any) => (
                                            <Tag key={a.name} color={a.required ? 'red' : 'default'}>
                                              {a.name}
                                              {a.required ? ' *' : ''}
                                            </Tag>
                                          ))}
                                        </Space>
                                      </div>
                                    )}
                                  </div>
                                }
                              />
                            </List.Item>
                          )}
                        />
                      )
                    }
                  ]}
                />
              )
            }))}
          />
        )}
      </Drawer>

      <Modal
        open={!!contentModal}
        title={contentModal?.title}
        width={760}
        onCancel={() => setContentModal(null)}
        footer={[
          <Button key="close" onClick={() => setContentModal(null)}>
            关闭
          </Button>,
          <Button
            key="use"
            type="primary"
            onClick={() => {
              if (contentModal) {
                onUse(`请基于以下资料回答：\n\n---\n${contentModal.content}\n---\n\n`);
                setContentModal(null);
                onClose();
              }
            }}
          >
            塞到输入框
          </Button>
        ]}
      >
        <pre
          style={{
            background: '#f6f8fa',
            padding: 12,
            borderRadius: 6,
            maxHeight: '60vh',
            overflow: 'auto',
            whiteSpace: 'pre-wrap',
            fontSize: 12
          }}
        >
          {contentModal?.content}
        </pre>
      </Modal>

      <Modal
        open={!!promptModal}
        title={`💡 使用 Prompt: ${promptModal?.prompt.name}`}
        onCancel={() => {
          setPromptModal(null);
          setPromptArgs({});
        }}
        onOk={handleGetPrompt}
        okText="获取并填充"
        cancelText="取消"
      >
        <div style={{ color: '#6b7280', marginBottom: 12 }}>{promptModal?.prompt.description}</div>
        <Form layout="vertical">
          {(promptModal?.prompt.arguments ?? []).map((arg: any) => (
            <Form.Item
              key={arg.name}
              label={
                <Space>
                  <span>{arg.name}</span>
                  {arg.required && <Tag color="red">必填</Tag>}
                </Space>
              }
              extra={arg.description}
            >
              <Input
                value={promptArgs[arg.name] || ''}
                onChange={(e) => setPromptArgs((p) => ({ ...p, [arg.name]: e.target.value }))}
              />
            </Form.Item>
          ))}
        </Form>
      </Modal>
    </>
  );
}
