import { useEffect, useMemo, useState } from 'react';
import { Modal, Input, Select, Tabs, Alert, Space, Button, App as AntApp } from 'antd';
import { SKILL_TEMPLATES } from '../skillTemplates';
import { AgentAPI } from '../api';

interface Props {
  open: boolean;
  agentId: string;
  skillId?: string | null;
  onClose: () => void;
  onSaved: () => void;
}

export default function SkillEditor({ open, agentId, skillId, onClose, onSaved }: Props) {
  const isNew = !skillId;
  const { message } = AntApp.useApp();
  const [content, setContent] = useState('');
  const [tplKey, setTplKey] = useState<'prompt' | 'http' | 'js'>('prompt');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    if (isNew) {
      setContent(SKILL_TEMPLATES.prompt.content);
      setTplKey('prompt');
    } else if (skillId) {
      AgentAPI.getSkill(agentId, skillId).then((d) => setContent(d.content || ''));
    }
  }, [open, skillId, isNew, agentId]);

  // 简单解析 frontmatter（仅前端预览用）
  const preview = useMemo(() => {
    const m = content.match(/^---\s*\n([\s\S]*?)\n---/);
    if (!m) return { warning: '⚠️ 未检测到 YAML frontmatter，将作为 prompt 类型注入' };
    const yaml = m[1];
    const get = (k: string) => {
      const r = new RegExp(`^${k}\\s*:\\s*(.+?)$`, 'm');
      return yaml.match(r)?.[1]?.trim();
    };
    return {
      name: get('name'),
      description: get('description'),
      type: get('type') || 'prompt',
      handler: get('handler')
    } as any;
  }, [content]);

  const handleSave = async () => {
    setSaving(true);
    try {
      if (isNew) {
        await AgentAPI.createSkill(agentId, {
          name: preview.name || 'skill',
          content
        });
        message.success('已创建');
      } else {
        await AgentAPI.updateSkill(agentId, skillId!, { content });
        message.success('已保存');
      }
      onSaved();
      onClose();
    } catch (e: any) {
      message.error('保存失败：' + (e?.message ?? e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      title={isNew ? '✨ 新建 Skill' : '✏️ 编辑 Skill'}
      width={920}
      onCancel={onClose}
      onOk={handleSave}
      okText="保存"
      cancelText="取消"
      confirmLoading={saving}
      destroyOnHidden
    >
      {isNew && (
        <Space style={{ marginBottom: 12 }}>
          <span style={{ color: '#6b7280' }}>从模板开始：</span>
          <Select
            value={tplKey}
            style={{ width: 280 }}
            onChange={(v) => {
              setTplKey(v);
              setContent(SKILL_TEMPLATES[v].content);
            }}
            options={Object.entries(SKILL_TEMPLATES).map(([k, v]) => ({
              value: k,
              label: v.label
            }))}
          />
          <Button
            size="small"
            onClick={() => {
              setContent(SKILL_TEMPLATES[tplKey].content);
            }}
          >
            重置
          </Button>
        </Space>
      )}

      <Tabs
        items={[
          {
            key: 'editor',
            label: '编辑器',
            children: (
              <Input.TextArea
                value={content}
                onChange={(e) => setContent(e.target.value)}
                style={{ fontFamily: 'Consolas, Menlo, monospace', fontSize: 13 }}
                autoSize={{ minRows: 18, maxRows: 26 }}
              />
            )
          },
          {
            key: 'meta',
            label: '解析预览',
            children: preview.warning ? (
              <Alert type="warning" message={preview.warning} />
            ) : (
              <div style={{ background: '#f9fafb', padding: 12, borderRadius: 6 }}>
                <div>
                  <b>name:</b> {preview.name || '(未声明)'}
                </div>
                <div>
                  <b>type:</b> {preview.type}
                </div>
                <div>
                  <b>description:</b> {preview.description || '(无)'}
                </div>
                {preview.handler && (
                  <div>
                    <b>handler:</b> {preview.handler}
                  </div>
                )}
                <Alert
                  style={{ marginTop: 12 }}
                  type="info"
                  message="保存后服务端会重新解析 frontmatter；type 必须是 prompt / http / js 之一。"
                />
              </div>
            )
          },
          {
            key: 'help',
            label: '语法说明',
            children: (
              <div style={{ fontSize: 13, lineHeight: 1.7 }}>
                <p>
                  Skill 是一个带 YAML frontmatter 的 Markdown 文件，frontmatter 用于声明工具元信息：
                </p>
                <pre style={{ background: '#f6f8fa', padding: 12, borderRadius: 6 }}>{`---
name: 工具内部名（仅字母数字下划线）
description: 给 LLM 看的功能描述
type: prompt | http | js
parameters:           # JSON Schema (function calling 标准)
  type: object
  properties:
    foo: { type: string }
  required: [foo]
handler: ...          # http: URL 模板  /  js: 代码体
config:               # 可选：method/headers/body/timeout/allowFetch
  method: GET
---`}</pre>
                <ul>
                  <li>
                    <b>prompt</b>：仅作 SOP 注入到 System Prompt，不会被 function calling
                  </li>
                  <li>
                    <b>http</b>：handler 是 URL 模板（<code>{'{{var}}'}</code> 替换参数），可配 method/headers/body
                  </li>
                  <li>
                    <b>js</b>：handler 是异步 JS 代码体，沙箱执行，可访问 <code>args</code>，需 <code>return</code> 结果
                  </li>
                </ul>
              </div>
            )
          }
        ]}
      />
    </Modal>
  );
}
