/**
 * 简化项目创建页面
 *
 * 设计理念：
 * 1. 收集项目基本信息（名称、集数）
 * 2. 支持直接输入创作文字或上传灵感文件
 * 3. 立即创建项目
 * 4. 其他内容（AI辅助生成）在项目详情页完成
 */
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, InputNumber, Button, Card, message, Space, Alert, Radio, Upload, Select } from 'antd'
import { FileTextOutlined, PlusOutlined, UploadOutlined, BulbOutlined, EditOutlined } from '@ant-design/icons'
import { useProjectStore } from '@/stores/projectStore'
import { ProjectCreateRequest } from '@/services/projectService'
import type { UploadFile } from 'antd'

const { TextArea } = Input
const { Option } = Select

export const ProjectCreateProgressive = () => {
  const navigate = useNavigate()
  const createProject = useProjectStore(state => state.createProject)

  // 项目状态
  const [creating, setCreating] = useState(false)
  const [creationMode, setCreationMode] = useState<'blank' | 'text' | 'file'>('blank')
  const [textContent, setTextContent] = useState('')
  const [uploadedFile, setUploadedFile] = useState<UploadFile | null>(null)
  const [inspirationType, setInspirationType] = useState<'story' | 'character' | 'scene' | 'dialogue'>('story')

  const [form] = Form.useForm()

  // 处理创作方式切换
  const handleModeChange = (newMode: 'blank' | 'text' | 'file') => {
    // 如果有内容且切换到不同模式，提示用户内容已保留
    if (creationMode !== newMode && (textContent || uploadedFile)) {
      const keptContent = creationMode === 'text' ? '文字内容' : '文件'
      message.info(`切换到${newMode === 'blank' ? '从头创作' : newMode === 'text' ? '直接输入' : '文件上传'}，${keptContent}已保留`)
    }
    setCreationMode(newMode)
  }

  // 创建项目
  const handleCreateProject = async () => {
    try {
      await form.validateFields()
      const name = form.getFieldValue('name')
      const totalEpisodes = form.getFieldValue('totalEpisodes') || 30

      // 验证创作内容
      if (creationMode === 'text' && !textContent.trim()) {
        message.error('请输入创作文字内容')
        return
      }
      if (creationMode === 'file' && !uploadedFile) {
        message.error('请上传灵感文件')
        return
      }

      setCreating(true)

      // 读取文件内容
      let fileContent = ''
      if (creationMode === 'file' && uploadedFile?.originFileObj) {
        fileContent = await uploadedFile.originFileObj.text()
      }

      const projectData: ProjectCreateRequest = {
        name: name.trim(),
        totalEpisodes,
        globalContext: {
          worldSetting: '',
          overallOutline: '',
          characterProfiles: {},
          sceneSettings: {},
          // 根据创作模式保存内容
          uploadedScript: creationMode === 'text' ? textContent : fileContent,
          inspiration: creationMode === 'file' ? inspirationType : undefined
        }
      }

      const project = await createProject(projectData)
      message.success('项目创建成功！')

      // 跳转到项目详情页
      navigate(`/projects/${project.id}`)
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return
      }
      console.error('创建项目失败:', error)
      message.error(`创建失败: ${error.message || '未知错误'}`)
    } finally {
      setCreating(false)
    }
  }

  return (
    <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
      {/* 头部 */}
      <Card style={{ marginBottom: '24px' }}>
        <Space direction="vertical" style={{ width: '100%' }} size="small">
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <FileTextOutlined style={{ fontSize: '20px', color: '#1677ff' }} />
            <h1 style={{ margin: 0, fontSize: '20px', fontWeight: 600 }}>创建新项目</h1>
          </div>
          <Alert
            message="填写基本信息后即可创建项目，后续内容可在项目详情页中完善"
            type="info"
            showIcon={false}
          />
        </Space>
      </Card>

      {/* 创建项目表单 */}
      <Card>
        <Form form={form} layout="vertical">
          <Form.Item
            label="项目名称"
            name="name"
            rules={[{ required: true, message: '请填写项目名称' }]}
          >
            <Input placeholder="例如：宫廷风云" size="large" />
          </Form.Item>

          <Form.Item
            label="总集数"
            name="totalEpisodes"
            initialValue={30}
            rules={[{ required: true, message: '请填写总集数' }]}
          >
            <InputNumber min={1} max={500} style={{ width: '100%' }} size="large" />
          </Form.Item>

          {/* 创作方式选择 */}
          <Form.Item label="创作方式">
            <Radio.Group
              value={creationMode}
              onChange={(e) => handleModeChange(e.target.value)}
              style={{ width: '100%' }}
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                <Radio value="blank">
                  <Space>
                    <FileTextOutlined />
                    <span>从头创作（稍后在详情页补充内容）</span>
                  </Space>
                </Radio>
                <Radio value="text">
                  <Space>
                    <EditOutlined />
                    <span>直接输入创作文字</span>
                  </Space>
                </Radio>
                <Radio value="file">
                  <Space>
                    <UploadOutlined />
                    <span>上传灵感文件</span>
                  </Space>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>

          {/* 直接输入文字 */}
          {creationMode === 'text' && (
            <Form.Item label="创作文字内容">
              <TextArea
                value={textContent}
                onChange={(e) => setTextContent(e.target.value)}
                placeholder="请输入您的创作文字、故事大纲、角色设定等内容..."
                rows={8}
                maxLength={10000}
                showCount
              />
              <Alert
                message="提示"
                description="输入的内容将作为创作基础，AI 将根据您的内容进行分析和扩展。"
                type="info"
                showIcon
                style={{ marginTop: '8px' }}
              />
            </Form.Item>
          )}

          {/* 上传灵感文件 */}
          {creationMode === 'file' && (
            <>
              <Form.Item label="灵感类型">
                <Select
                  value={inspirationType}
                  onChange={setInspirationType}
                  style={{ width: '100%' }}
                >
                  <Option value="story">
                    <Space>
                      <BulbOutlined />
                      故事灵感
                    </Space>
                  </Option>
                  <Option value="character">角色设定</Option>
                  <Option value="scene">场景描述</Option>
                  <Option value="dialogue">对话片段</Option>
                </Select>
              </Form.Item>

              <Form.Item label="上传文件">
                <Upload
                  accept=".txt,.md,.doc,.docx"
                  maxCount={1}
                  fileList={uploadedFile ? [uploadedFile] : []}
                  beforeUpload={(file) => {
                    setUploadedFile(file)
                    return false // 阻止自动上传
                  }}
                  onRemove={() => setUploadedFile(null)}
                >
                  <Button icon={<UploadOutlined />} disabled={uploadedFile !== null}>
                    {uploadedFile ? '已选择文件' : '选择文件（支持 .txt, .md, .doc, .docx）'}
                  </Button>
                </Upload>
                {uploadedFile && (
                  <div style={{ marginTop: '8px', fontSize: '12px', color: '#52c41a' }}>
                    ✓ 已选择: {uploadedFile.name}
                  </div>
                )}
                <Alert
                  message="提示"
                  description="上传的文件内容将被读取并作为创作灵感。支持文本文件和 Word 文档。"
                  type="info"
                  showIcon
                  style={{ marginTop: '8px' }}
                />
              </Form.Item>
            </>
          )}

          {/* 显示已保存内容的提示 */}
          {creationMode !== 'blank' && (textContent || uploadedFile) && (
            <Alert
              message="已准备就绪"
              description={
                creationMode === 'text'
                  ? `已输入 ${textContent.length} 个字符的创作内容`
                  : uploadedFile
                  ? `已上传文件: ${uploadedFile.name}`
                  : ''
              }
              type="success"
              showIcon
              style={{ marginBottom: '16px' }}
            />
          )}

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'space-between' }}>
              <Button onClick={() => navigate('/projects')}>
                取消
              </Button>
              <Button
                type="primary"
                size="large"
                icon={<PlusOutlined />}
                loading={creating}
                onClick={handleCreateProject}
              >
                创建项目
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default ProjectCreateProgressive
