/**
 * 项目创建页面
 */
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Form, Input, InputNumber, Button, Card, Steps, message, Spin } from 'antd'
import { ProjectCreateRequest, useProjectStore } from '@/stores/projectStore'

const { Step } = Steps
const { TextArea } = Input

export const ProjectCreate = () => {
  const navigate = useNavigate()
  const createProject = useProjectStore(state => state.createProject)
  const [currentStep, setCurrentStep] = useState(0)
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm()

  const steps = [
    {
      title: '基本信息',
      content: (
        <>
          <Form.Item label="项目名称" name="name" rules={[{ required: true, message: '请输入项目名称' }]}>
            <Input placeholder="例如：宫廷风云" />
          </Form.Item>
          <Form.Item label="总集数" name="totalEpisodes" initialValue={30} rules={[{ required: true }]}>
            <InputNumber min={1} max={100} style={{ width: '100%' }} />
          </Form.Item>
        </>
      )
    },
    {
      title: '世界观设定',
      content: (
        <>
          <Form.Item label="世界观设定" name={['globalContext', 'worldSetting']}>
            <TextArea rows={4} placeholder="例如：架空朝代天启朝，皇权与相权之争..." />
          </Form.Item>
          <Form.Item label="风格指南" name={['globalContext', 'styleGuide']}>
            <TextArea rows={2} placeholder="例如：古风正剧，对话半文半白..." />
          </Form.Item>
        </>
      )
    },
    {
      title: '人物设定',
      content: (
        <Form.Item label="主要人物" name="charactersDescription">
          <TextArea rows={6} placeholder="例如：&#10;李云飞：边关将军，耿直刚正，说话简练直接&#10;苏婉儿：丞相之女，聪慧隐忍，说话含蓄委婉" />
        </Form.Item>
      )
    },
    {
      title: '整体大纲',
      content: (
        <Form.Item label="整体大纲" name={['globalContext', 'overallOutline']}>
          <TextArea rows={6} placeholder="例如：&#10;EP01-05：相识与相恋，两人被迫分离&#10;EP06-15：宫中斗争，婉儿周旋，云飞征战&#10;EP16-25：真相大白，联手对抗丞相&#10;EP26-30：最终对决，有情人终成眷属" />
        </Form.Item>
      )
    }
  ]

  const handleSubmit = async (values: any) => {
    setLoading(true)
    try {
      // 构建项目数据
      const projectData: ProjectCreateRequest = {
        name: values.name,
        totalEpisodes: values.totalEpisodes,
        mode: 'batch',
        globalContext: {
          worldSetting: values.globalContext?.worldSetting || '',
          styleGuide: values.globalContext?.styleGuide || '',
          overallOutline: values.globalContext?.overallOutline || '',
          characterProfiles: {},
          sceneSettings: {}
        }
      }

      // 简单解析人物描述
      if (values.charactersDescription) {
        const lines = values.charactersDescription.split('\n').filter(l => l.trim())
        lines.forEach((line: string, idx: number) => {
          const match = line.match(/([^：:]+)[：:](.+)/)
          if (match) {
            projectData.globalContext!.characterProfiles![`char_${idx}`] = {
              name: match[1].trim(),
              description: match[2].trim(),
              personality: '',
              speechStyle: ''
            }
          }
        })
      }

      const project = await createProject(projectData)
      message.success('项目创建成功！')
      navigate(`/projects/${project.id}`)
    } catch (error) {
      message.error(`创建失败: ${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
      <Card title="创建新的剧集项目">
        <Steps current={currentStep} style={{ marginBottom: '24px' }}>
          {steps.map((s, i) => <Step key={i} title={s.title} />)}
        </Steps>

        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          {steps[currentStep].content}

          <div style={{ marginTop: '24px', display: 'flex', justifyContent: 'space-between' }}>
            {currentStep > 0 && (
              <Button onClick={() => setCurrentStep(currentStep - 1)}>
                上一步
              </Button>
            )}
            <div style={{ marginLeft: 'auto' }}>
              {currentStep < steps.length - 1 ? (
                <Button type="primary" onClick={() => setCurrentStep(currentStep + 1)}>
                  下一步
                </Button>
              ) : (
                <Button type="primary" htmlType="submit" loading={loading}>
                  创建项目
                </Button>
              )}
            </div>
          </div>
        </Form>
      </Card>
    </div>
  )
}
