/**
 * Skill 创建向导 - 多步骤创建流程
 *
 * 完整的 Skill 创建流程：
 * 1. 从模板初始化
 * 2. 填写基础信息
 * 3. 编辑行为指导
 * 4. 上传参考文件
 * 5. 预览和保存
 */
import { useState, useEffect } from 'react'
import {
  Modal,
  Steps,
  Form,
  Input,
  Select,
  Button,
  Space,
  Card,
  Alert,
  Upload,
  Tag,
  List,
  message,
  Spin,
  Divider,
  Typography,
  Row,
  Col,
  Progress,
  Tabs,
  Radio
} from 'antd'
import {
  AppstoreOutlined,
  EditOutlined,
  FileTextOutlined,
  UploadOutlined,
  CheckCircleOutlined,
  DeleteOutlined,
  EyeOutlined,
  InboxOutlined,
  RobotOutlined,
  ThunderboltOutlined
} from '@ant-design/icons'
import { skillService, uploadService, SkillGenerateRequest, SkillGenerateResponse } from '@/services'
import type { UploadFile, UploadProps } from 'antd/es/upload/interface'
import type { ReferenceFile } from '@/services/uploadService'

const { Step } = Steps
const { TextArea } = Input
const { Option } = Select
const { Text, Title, Paragraph } = Typography
const { Dragger } = Upload
const { TabPane } = Tabs

interface SkillCreateWizardProps {
  visible: boolean
  onClose: () => void
  onSuccess: () => void
}

interface WizardFormData {
  id: string
  name: string
  category: string
  behavior_guide: string
  tags: string[]
}

export const SkillCreateWizard: React.FC<SkillCreateWizardProps> = ({
  visible,
  onClose,
  onSuccess
}) => {
  // 当前步骤
  const [currentStep, setCurrentStep] = useState(0)

  // 表单数据和状态
  const [form] = Form.useForm<WizardFormData>()
  const [skillId, setSkillId] = useState('')
  const [skillName, setSkillName] = useState('')
  const [initializing, setInitializing] = useState(false)
  const [initSuccess, setInitSuccess] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  // AI 生成相关状态
  const [createMode, setCreateMode] = useState<'manual' | 'ai'>('manual')
  const [aiGenerating, setAiGenerating] = useState(false)
  const [aiDescription, setAiDescription] = useState('')
  const [aiGenerated, setAiGenerated] = useState<SkillGenerateResponse | null>(null)

  // 参考文件上传
  const [referenceFiles, setReferenceFiles] = useState<ReferenceFile[]>([])
  const [uploading, setUploading] = useState(false)
  const [fileList, setFileList] = useState<UploadFile[]>([])

  // 重置表单
  const resetWizard = () => {
    setCurrentStep(0)
    form.resetFields()
    setSkillId('')
    setSkillName('')
    setInitSuccess(false)
    setCreateMode('manual')
    setAiDescription('')
    setAiGenerated(null)
    setReferenceFiles([])
    setFileList([])
  }

  // 关闭时重置
  useEffect(() => {
    if (!visible) {
      resetWizard()
    }
  }, [visible])

  // 步骤1: 初始化 Skill 模板
  const handleInitSkill = async () => {
    const id = form.getFieldValue('id')
    const name = form.getFieldValue('name')

    if (!id || !name) {
      message.warning('请填写 Skill ID 和名称')
      return
    }

    // 验证格式
    if (!/^[a-z0-9-]+$/.test(id)) {
      message.warning('Skill ID 只能包含小写字母、数字和连字符')
      return
    }

    setInitializing(true)
    try {
      const result = await skillService.initSkillTemplate(id)

      if (result.success) {
        setSkillId(id)
        setSkillName(name)
        setInitSuccess(true)
        message.success('Skill 模板初始化成功！')

        // 自动填充行为指导模板
        form.setFieldsValue({
          behavior_guide: `# ${name}\n\n## Overview\n\n[TODO: 描述这个 Skill 的功能]\n\n## Core Principles\n\n[TODO: 添加核心原则]\n\n## Usage\n\n[TODO: 说明何时使用这个 Skill]\n\n## Output Format\n\n[TODO: 说明输出格式]`
        })

        // 进入下一步
        setCurrentStep(1)
      }
    } catch (error) {
      message.error(`初始化失败: ${(error as Error).message}`)
    } finally {
      setInitializing(false)
    }
  }

  // AI 生成 Skill
  const handleAIGenerate = async () => {
    if (!aiDescription.trim()) {
      message.warning('请描述你想要创建的 Skill')
      return
    }

    setAiGenerating(true)
    try {
      const request: SkillGenerateRequest = {
        description: aiDescription,
        category: form.getFieldValue('category'),
        tags: form.getFieldValue('tags'),
        temperature: 0.7
      }

      const result = await skillService.generateSkill(request)

      setAiGenerated(result)
      setSkillId(result.suggested_id)
      setSkillName(result.suggested_name)

      // 填充表单
      form.setFieldsValue({
        id: result.suggested_id,
        name: result.suggested_name,
        category: result.category,
        behavior_guide: result.skill_content,
        tags: result.suggested_tags
      })

      setInitSuccess(true)
      message.success('AI 生成成功！您可以继续编辑或直接保存')

      // 进入下一步
      setCurrentStep(1)
    } catch (error) {
      message.error(`AI 生成失败: ${(error as Error).message}`)
    } finally {
      setAiGenerating(false)
    }
  }

  // 步骤2: 完成基础信息
  const handleFinishBasicInfo = async () => {
    try {
      await form.validateFields(['id', 'name', 'category'])
      setCurrentStep(2)
    } catch (error) {
      message.warning('请完成必填项')
    }
  }

  // 步骤3: 完成行为指导
  const handleFinishBehaviorGuide = () => {
    const behaviorGuide = form.getFieldValue('behavior_guide')
    if (!behaviorGuide || behaviorGuide.trim().length < 50) {
      message.warning('请输入至少 50 字的行为指导内容')
      return
    }
    setCurrentStep(3)
    // 加载已上传的参考文件
    loadReferenceFiles()
  }

  // 加载参考文件列表
  const loadReferenceFiles = async () => {
    const id = form.getFieldValue('id')
    if (!id) return

    try {
      const result = await uploadService.listReferenceFiles(id)
      setReferenceFiles(result.files || [])
    } catch (error) {
      console.error('加载参考文件失败:', error)
    }
  }

  // 文件上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    fileList,
    accept: '.md,.txt,.json,.yaml,.yml,.pdf,.doc,.docx',
    beforeUpload: () => false, // 阻止自动上传
    onChange: ({ fileList: newFileList }) => {
      setFileList(newFileList)
    },
    onRemove: () => {
      setFileList([])
    }
  }

  // 上传参考文件
  const handleUploadReferenceFiles = async () => {
    if (fileList.length === 0) {
      setCurrentStep(4)
      return
    }

    const id = form.getFieldValue('id')
    setUploading(true)

    try {
      for (const file of fileList) {
        const result = await uploadService.uploadReferenceFile(id, file.originFileObj as File)
        if (result.success) {
          message.success(`文件 ${file.name} 上传成功`)
        }
      }

      // 重新加载文件列表
      await loadReferenceFiles()
      setFileList([])
      setCurrentStep(4)
      message.success('所有文件上传成功')
    } catch (error) {
      message.error(`文件上传失败: ${(error as Error).message}`)
    } finally {
      setUploading(false)
    }
  }

  // 删除参考文件
  const handleDeleteReferenceFile = async (filename: string) => {
    const id = form.getFieldValue('id')
    try {
      await uploadService.deleteReferenceFile(id, filename)
      message.success('文件删除成功')
      loadReferenceFiles()
    } catch (error) {
      message.error(`删除失败: ${(error as Error).message}`)
    }
  }

  // 最终保存 Skill
  const handleSaveSkill = async () => {
    try {
      const values = await form.validateFields()
      setSubmitting(true)

      await skillService.createSkill({
        id: values.id,
        name: values.name,
        content: values.behavior_guide,
        category: values.category
      })

      message.success('Skill 创建成功！')
      onSuccess()
      onClose()
      resetWizard()
    } catch (error) {
      message.error(`保存失败: ${(error as Error).message}`)
    } finally {
      setSubmitting(false)
    }
  }

  // 步骤内容
  const steps = [
    {
      title: '创建方式',
      description: '选择创建 Skill 的方式',
      icon: <AppstoreOutlined />,
      content: (
        <Card title="步骤 1: 选择创建方式" size="small">
          <Tabs
            activeKey={createMode}
            onChange={(key) => setCreateMode(key as 'manual' | 'ai')}
            items={[
              {
                key: 'manual',
                label: '手动创建',
                icon: <EditOutlined />,
                children: (
                  <div>
                    <Alert
                      message="手动创建 Skill 模板"
                      description="使用 skill-creator 脚本创建标准目录结构，手动填写内容"
                      type="info"
                      showIcon
                      style={{ marginBottom: '16px' }}
                    />

                    <Form form={form} layout="vertical">
                      <Form.Item
                        label="Skill ID"
                        name="id"
                        rules={[
                          { required: true, message: '请输入 Skill ID' },
                          { pattern: /^[a-z0-9-]+$/, message: '只能包含小写字母、数字和连字符' }
                        ]}
                        extra="hyphen-case 格式，如: my-awesome-skill"
                      >
                        <Input placeholder="例如: my-awesome-skill" prefix={<AppstoreOutlined />} />
                      </Form.Item>

                      <Form.Item
                        label="Skill 名称"
                        name="name"
                        rules={[{ required: true, message: '请输入 Skill 名称' }]}
                      >
                        <Input placeholder="例如: 我的自定义 Skill" />
                      </Form.Item>

                      <Form.Item
                        label="分类"
                        name="category"
                        rules={[{ required: true, message: '请选择分类' }]}
                      >
                        <Select placeholder="选择分类">
                          <Option value="writing">写作</Option>
                          <Option value="dialogue">对话</Option>
                          <Option value="analysis">分析</Option>
                          <Option value="translation">翻译</Option>
                          <Option value="review">审核</Option>
                          <Option value="general">通用</Option>
                        </Select>
                      </Form.Item>
                    </Form>

                    <Button
                      type="primary"
                      size="large"
                      block
                      icon={<AppstoreOutlined />}
                      loading={initializing}
                      onClick={handleInitSkill}
                    >
                      初始化 Skill 模板
                    </Button>
                  </div>
                )
              },
              {
                key: 'ai',
                label: 'AI 生成',
                icon: <RobotOutlined />,
                children: (
                  <div>
                    <Alert
                      message="使用 AI 生成 Skill"
                      description="AI 会根据你的描述，按照 skill-creator 标准自动生成 Skill 内容"
                      type="info"
                      showIcon
                      style={{ marginBottom: '16px' }}
                    />

                    <Form form={form} layout="vertical">
                      <Form.Item
                        label="描述你想要的 Skill"
                        extra="例如：我想创建一个古风对话创作的 Skill，需要让角色说话符合古代身份和性格"
                      >
                        <TextArea
                          value={aiDescription}
                          onChange={(e) => setAiDescription(e.target.value)}
                          placeholder="描述你想要创建的 Skill 功能和要求..."
                          rows={4}
                        />
                      </Form.Item>

                      <Form.Item
                        label="分类（可选）"
                        name="category"
                      >
                        <Select placeholder="选择分类">
                          <Option value="writing">写作</Option>
                          <Option value="dialogue">对话</Option>
                          <Option value="analysis">分析</Option>
                          <Option value="translation">翻译</Option>
                          <Option value="review">审核</Option>
                          <Option value="general">通用</Option>
                        </Select>
                      </Form.Item>

                      <Form.Item
                        label="标签（可选）"
                        name="tags"
                      >
                        <Select mode="tags" placeholder="输入标签，按回车添加" />
                      </Form.Item>
                    </Form>

                    <Space direction="vertical" style={{ width: '100%' }}>
                      <Button
                        type="primary"
                        size="large"
                        block
                        icon={<ThunderboltOutlined />}
                        loading={aiGenerating}
                        onClick={handleAIGenerate}
                        disabled={!aiDescription.trim()}
                      >
                        AI 生成 Skill
                      </Button>

                      {aiGenerated && (
                        <Alert
                          message="AI 生成成功！"
                          description={
                            <div>
                              <p><strong>Suggested ID:</strong> {aiGenerated.suggested_id}</p>
                              <p><strong>Name:</strong> {aiGenerated.suggested_name}</p>
                              <p><strong>Explanation:</strong> {aiGenerated.explanation}</p>
                              <p style={{ marginTop: '8px', fontSize: '12px', color: '#999' }}>
                                点击上方按钮继续编辑，或直接保存
                              </p>
                            </div>
                          }
                          type="success"
                          showIcon
                        />
                      )}
                    </Space>
                  </div>
                )
              }
            ]}
          />
        </Card>
      )
    },
    {
      title: '基础信息',
      description: '完善基本信息',
      icon: <EditOutlined />,
      content: (
        <Card title="步骤 2: 完善基础信息" size="small">
          <Alert
            message="Skill 模板已创建成功"
            description={`Skill ID: ${skillId || form.getFieldValue('id')}`}
            type="success"
            showIcon
            style={{ marginBottom: '16px' }}
          />

          <Form form={form} layout="vertical">
            <Form.Item label="Skill ID" name="id">
              <Input disabled prefix={<AppstoreOutlined />} />
            </Form.Item>

            <Form.Item
              label="Skill 名称"
              name="name"
              rules={[{ required: true, message: '请输入 Skill 名称' }]}
            >
              <Input placeholder="Skill 显示名称" />
            </Form.Item>

            <Form.Item
              label="分类"
              name="category"
              rules={[{ required: true, message: '请选择分类' }]}
            >
              <Select>
                <Option value="writing">写作</Option>
                <Option value="dialogue">对话</Option>
                <Option value="analysis">分析</Option>
                <Option value="translation">翻译</Option>
                <Option value="review">审核</Option>
                <Option value="general">通用</Option>
              </Select>
            </Form.Item>

            <Form.Item label="标签" name="tags">
              <Select mode="tags" placeholder="输入标签后按回车" />
            </Form.Item>
          </Form>

          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={() => setCurrentStep(0)}>上一步</Button>
            <Button type="primary" onClick={handleFinishBasicInfo}>下一步</Button>
          </Space>
        </Card>
      )
    },
    {
      title: '行为指导',
      description: '编辑核心内容',
      icon: <FileTextOutlined />,
      content: (
        <Card title="步骤 3: 编辑行为指导 (核心)" size="small">
          <Alert
            message="行为指导是 Skill 的核心"
            description="这些内容将被注入到 LLM 的 System Prompt 中，指导 AI 如何执行任务"
            type="info"
            showIcon
            style={{ marginBottom: '16px' }}
          />

          <Form form={form} layout="vertical">
            <Form.Item
              label="行为指导内容 (Markdown 格式)"
              name="behavior_guide"
              rules={[{ required: true, message: '请输入行为指导' }]}
              extra="支持 Markdown 格式，建议包含 Overview、Core Principles、Usage、Output Format 等部分"
            >
              <TextArea
                rows={16}
                placeholder="输入详细的行为指导..."
                style={{ fontFamily: 'monospace', fontSize: '13px' }}
              />
            </Form.Item>
          </Form>

          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={() => setCurrentStep(1)}>上一步</Button>
            <Button type="primary" onClick={handleFinishBehaviorGuide}>下一步</Button>
          </Space>
        </Card>
      )
    },
    {
      title: '参考文件',
      description: '上传参考资料',
      icon: <UploadOutlined />,
      content: (
        <Card title="步骤 4: 上传参考文件 (可选)" size="small">
          <Alert
            message="参考文件将被保存在 Skill 的 references/ 目录"
            description="支持 .md, .txt, .json, .yaml, .yml, .pdf, .doc, .docx 格式"
            type="info"
            showIcon
            style={{ marginBottom: '16px' }}
          />

          {/* 已上传文件列表 */}
          {referenceFiles.length > 0 && (
            <>
              <Divider orientation="left">已上传文件</Divider>
              <List
                size="small"
                dataSource={referenceFiles}
                renderItem={(file) => (
                  <List.Item
                    actions={[
                      <Button
                        type="link"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteReferenceFile(file.name)}
                      >
                        删除
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<FileTextOutlined />}
                      title={file.name}
                      description={`${(file.size / 1024).toFixed(2)} KB`}
                    />
                  </List.Item>
                )}
              />
              <Divider />
            </>
          )}

          {/* 上传新文件 */}
          <Dragger {...uploadProps} style={{ marginBottom: '16px' }}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p className="ant-upload-hint">
              支持单个或批量上传。严禁上传公司数据或其他敏感文件。
            </p>
          </Dragger>

          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={() => setCurrentStep(2)}>上一步</Button>
            <Button
              type="primary"
              icon={<UploadOutlined />}
              loading={uploading}
              onClick={handleUploadReferenceFiles}
            >
              {fileList.length > 0 ? '上传文件并继续' : '跳过（暂不上传）'}
            </Button>
          </Space>
        </Card>
      )
    },
    {
      title: '预览确认',
      description: '预览并保存',
      icon: <CheckCircleOutlined />,
      content: (
        <Card title="步骤 5: 预览并确认" size="small">
          <Alert
            message="请确认 Skill 信息无误后保存"
            description="保存后 Skill 将立即可用于项目创作"
            type="success"
            showIcon
            style={{ marginBottom: '16px' }}
          />

          <Row gutter={16}>
            <Col span={12}>
              <Card size="small" title="基础信息" type="inner">
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div>
                    <Text type="secondary">Skill ID:</Text>
                    <br />
                    <Text code>{form.getFieldValue('id')}</Text>
                  </div>
                  <div>
                    <Text type="secondary">名称:</Text>
                    <br />
                    <Text>{form.getFieldValue('name')}</Text>
                  </div>
                  <div>
                    <Text type="secondary">分类:</Text>
                    <br />
                    <Tag>{form.getFieldValue('category')}</Tag>
                  </div>
                  <div>
                    <Text type="secondary">标签:</Text>
                    <br />
                    <Space size={[4, 4]} wrap>
                      {form.getFieldValue('tags')?.map((tag: string) => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </Space>
                  </div>
                  <div>
                    <Text type="secondary">参考文件:</Text>
                    <br />
                    <Text>{referenceFiles.length} 个文件</Text>
                  </div>
                </Space>
              </Card>
            </Col>

            <Col span={12}>
              <Card size="small" title="行为指导预览" type="inner">
                <div style={{
                  background: '#f5f5f5',
                  padding: '12px',
                  borderRadius: '4px',
                  maxHeight: '300px',
                  overflowY: 'auto',
                  fontSize: '12px',
                  whiteSpace: 'pre-wrap'
                }}>
                  {form.getFieldValue('behavior_guide')?.substring(0, 500)}
                  {form.getFieldValue('behavior_guide')?.length > 500 && '...'}
                </div>
              </Card>
            </Col>
          </Row>

          <Space style={{ width: '100%', justifyContent: 'flex-end', marginTop: '16px' }}>
            <Button onClick={() => setCurrentStep(3)}>上一步</Button>
            <Button onClick={onClose}>取消</Button>
            <Button
              type="primary"
              size="large"
              icon={<CheckCircleOutlined />}
              loading={submitting}
              onClick={handleSaveSkill}
            >
              创建 Skill
            </Button>
          </Space>
        </Card>
      )
    }
  ]

  return (
    <Modal
      title={
        <Space>
          <AppstoreOutlined />
          <span>创建 Skill - 多步骤向导</span>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={900}
      footer={null}
      destroyOnClose
    >
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* 进度条 */}
        <Steps current={currentStep} size="small">
          {steps.map((step, index) => (
            <Step
              key={index}
              title={step.title}
              description={step.description}
              icon={step.icon}
            />
          ))}
        </Steps>

        {/* 当前步骤内容 */}
        <div style={{ minHeight: '400px' }}>
          {steps[currentStep].content}
        </div>
      </Space>
    </Modal>
  )
}
