import {
  ArrowLeft,
  ArrowRight,
  BookOpen,
  Check,
  CheckCircle2,
  FileCheck,
  Flame,
  Info,
  Layers,
  Sparkles,
  Users,
  Video,
  Volume2,
  Wand2,
  X
} from 'lucide-react'
import { FormEvent, useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api } from '../api'
import { COURSE_TEMPLATES, type CourseTemplate } from '../data/courseTemplates'

const DEFAULT_COURSE_DESCRIPTION = `【课程简介】本课程围绕核心主题展开，通过清晰的知识讲解与案例说明，帮助学习者理解并掌握课程重点。
【制作要求】采用“讲师讲解 + PPT课件”的形式，画面简洁清晰，内容层次分明；讲解自然流畅，重点内容配合字幕或图示呈现；视频建议使用16:9横屏、1080P高清规格。`

export function NewCourse() {
  const navigate = useNavigate()
  const [templates, setTemplates] = useState<CourseTemplate[]>(COURSE_TEMPLATES)
  const [selectedTemplateId, setSelectedTemplateId] = useState<string>(COURSE_TEMPLATES[0].id)
  const [activeTab, setActiveTab] = useState<'form' | 'templates'>('form')

  // 表单状态
  const [name, setName] = useState('')
  const [category, setCategory] = useState('党政专题')
  const [description, setDescription] = useState(DEFAULT_COURSE_DESCRIPTION)

  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')
  const [filledNotice, setFilledNotice] = useState('')
  const [detailModalOpen, setDetailModalOpen] = useState(false)

  const currentTemplate = templates.find((t) => t.id === selectedTemplateId) || templates[0]

  useEffect(() => {
    api
      .getTemplates()
      .then((r) => {
        if (r.templates && r.templates.length > 0) {
          setTemplates(r.templates)
        }
      })
      .catch(() => {
        // 使用默认本地配置
      })
  }, [])

  // 1. 一键填入表单
  function handleFillTemplate(tmpl: CourseTemplate = currentTemplate) {
    setName(tmpl.name)
    setCategory(tmpl.category)
    setDescription(tmpl.description)
    setFilledNotice(`已填入示例《${tmpl.name}》内容，您可按需进行调整。`)
    setTimeout(() => setFilledNotice(''), 4500)
  }

  // 2. 一键以此模板创建完整项目
  async function handleCreateFromTemplate(tmpl: CourseTemplate = currentTemplate) {
    setBusy(true)
    setError('')
    try {
      const { course } = await api.createFromTemplate(tmpl.id)
      navigate(`/courses/${course.id}`)
    } catch (x) {
      setError((x as Error).message)
      setBusy(false)
    }
  }

  // 3. 普通手动表单提交
  async function submit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setBusy(true)
    setError('')
    try {
      const { course } = await api.createCourse({
        name: name.trim(),
        category,
        description: description.trim()
      })
      navigate(`/courses/${course.id}`)
    } catch (x) {
      setError((x as Error).message)
      setBusy(false)
    }
  }

  return (
    <div className="page form-page">
      <Link to="/" className="back-link">
        <ArrowLeft size={16} />返回我的课程
      </Link>

      <div className="form-layout new-course-layout">
        {/* 左侧说明与精选示例区域 */}
        <aside className="new-course-aside">
          <span className="step-number">01</span>
          <p className="eyebrow">
            <Sparkles size={13} /> 创建课程
          </p>
          <h1>
            先告诉我们，<br />
            这是一门什么课。
          </h1>
          <p className="aside-subtext">
            填写基本信息后，可继续添加课程资产和讲师；也可以参考下方制作示例快速开始。
          </p>

          {/* 示范模版精选卡片 */}
          <div className="template-showcase-box">
            <div className="template-box-header">
              <div className="header-left">
                <Flame size={16} className="flame-icon" />
                <strong>制作示例</strong>
              </div>
            </div>

            {/* 模板切换标签（支持未来扩展） */}
            <div className="template-pills">
              {templates.map((tmpl) => (
                <button
                  key={tmpl.id}
                  type="button"
                  className={`template-pill ${tmpl.id === currentTemplate.id ? 'active' : ''}`}
                  onClick={() => setSelectedTemplateId(tmpl.id)}
                >
                  {tmpl.badge && <span className="pill-badge">{tmpl.badge}</span>}
                  {tmpl.category}
                </button>
              ))}
            </div>

            {/* 当前选中模版内容卡片 */}
            <div className="selected-template-card">
              <div className="card-top">
                <h3 className="sample-title">{currentTemplate.name}</h3>
                <p className="sample-desc">{currentTemplate.summary}</p>
              </div>

              {/* 关键规格参数列表 */}
              <div className="specs-grid">
                <div className="spec-item">
                  <Video size={13} />
                  <div>
                    <small>分辨率与画面</small>
                    <span>{currentTemplate.keySpecs.resolution}</span>
                  </div>
                </div>
                <div className="spec-item">
                  <Layers size={13} />
                  <div>
                    <small>讲师与课件比例</small>
                    <span>{currentTemplate.keySpecs.presenterRatio}</span>
                  </div>
                </div>
                <div className="spec-item">
                  <Volume2 size={13} />
                  <div>
                    <small>语速与节奏控制</small>
                    <span>{currentTemplate.keySpecs.speechSpeed}</span>
                  </div>
                </div>
              </div>

              {/* 模版操作按钮组 */}
              <div className="template-actions">
                <button
                  type="button"
                  className="secondary-button small-button action-btn"
                  onClick={() => handleFillTemplate(currentTemplate)}
                  title="将该示例的内容填入右侧表单，可自行修改"
                >
                  <Wand2 size={14} /> 填入当前表单
                </button>
                <button
                  type="button"
                  className="primary-button small-button action-btn highlight-sample-btn"
                  disabled={busy}
                  onClick={() => handleCreateFromTemplate(currentTemplate)}
                  title="直接创建完整示范课程，并自动导入讲师与课件素材"
                >
                  <Sparkles size={14} /> 一键使用此示例
                </button>
              </div>

              <div className="template-card-footer">
                <button
                  type="button"
                  className="detail-link-btn"
                  onClick={() => setDetailModalOpen(true)}
                >
                  <Info size={13} /> 查看完整任务书制作规范与验收标准 &raquo;
                </button>
              </div>
            </div>
          </div>
        </aside>

        {/* 右侧表单区域 */}
        <div className="new-course-main">
          {filledNotice && (
            <div className="filled-toast">
              <CheckCircle2 size={16} />
              <span>{filledNotice}</span>
            </div>
          )}

          <form className="paper-form" onSubmit={submit}>
            <div className="form-title">
              <div className="title-left">
                <span>COURSE PROFILE</span>
                <h2>课程基本信息</h2>
              </div>
            </div>

            <label>
              <span>课程名称 <b>*</b></span>
              <input
                name="name"
                required
                maxLength={100}
                placeholder="例如：坚持人民至上根本立场党课视频"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </label>

            <label>
              <span>课程分类</span>
              <select
                name="category"
                value={category}
                onChange={(e) => setCategory(e.target.value)}
              >
                <option value="党政专题">党政专题</option>
                <option value="高校公开课">高校公开课</option>
                <option value="企业培训">企业培训</option>
                <option value="职业教育">职业教育</option>
                <option value="其他">其他</option>
              </select>
            </label>

            <label>
              <span>课程简介与制作要求</span>
              <textarea
                name="description"
                rows={7}
                maxLength={1000}
                placeholder="填写课程概述、目标人群、运镜风格（如30%出镜/70%课件）、语速要求（如210-225字/分）或技术规格要求等..."
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </label>

            {error && <p className="form-error">{error}</p>}

            <div className="form-footer">
              <span>下一步：添加课程资产与讲师</span>
              <button className="primary-button" disabled={busy || !name.trim()}>
                {busy ? '正在创建…' : '继续'}
                <ArrowRight size={17} />
              </button>
            </div>
          </form>
        </div>
      </div>

      {/* 完整制作任务书与技术标准弹窗 */}
      {detailModalOpen && (
        <div className="modal-backdrop" onClick={() => setDetailModalOpen(false)}>
          <div className="modal-dialog brief-modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <div>
                <span className="modal-badge">{currentTemplate.badge || '制作示范'}</span>
                <h3>{currentTemplate.name} · 制作任务书</h3>
              </div>
              <button
                type="button"
                className="close-modal-btn"
                onClick={() => setDetailModalOpen(false)}
              >
                <X size={18} />
              </button>
            </div>

            <div className="modal-body brief-modal-content">
              {/* 核心重点 */}
              <div className="brief-section focus-card">
                <h4>
                  <Flame size={15} /> 核心重点要求
                </h4>
                <ul>
                  {currentTemplate.taskBrief.focalPoints.map((pt, i) => (
                    <li key={i}>{pt}</li>
                  ))}
                </ul>
              </div>

              {/* 项目目标 */}
              <div className="brief-section">
                <h4>
                  <FileCheck size={15} /> 项目目标与规格
                </h4>
                <ul>
                  {currentTemplate.taskBrief.goals.map((g, i) => (
                    <li key={i}>{g}</li>
                  ))}
                </ul>
              </div>

              {/* 画面与运镜节奏 */}
              <div className="brief-section">
                <h4>
                  <Video size={15} /> 画面运镜与语速控制
                </h4>
                <ul>
                  {currentTemplate.taskBrief.cameraAndPacing.map((c, i) => (
                    <li key={i}>{c}</li>
                  ))}
                </ul>
              </div>

              {/* 验收标准 */}
              <div className="brief-section">
                <h4>
                  <CheckCircle2 size={15} /> 交付与验收标准
                </h4>
                <ul>
                  {currentTemplate.taskBrief.acceptanceCriteria.map((a, i) => (
                    <li key={i}>{a}</li>
                  ))}
                </ul>
              </div>

              {/* 预置素材与讲师概览 */}
              <div className="brief-section">
                <h4>
                  <Users size={15} /> 示范配置一览
                </h4>
                <div className="brief-preset-grid">
                  <div className="brief-subcard">
                    <strong>示范讲师</strong>
                    {currentTemplate.instructors.map((inst, i) => (
                      <div key={i} className="inst-subrow">
                        <span>{inst.name}</span>
                        <small>{inst.organization}</small>
                        <p>{inst.introduction}</p>
                      </div>
                    ))}
                  </div>
                  {currentTemplate.episodes && currentTemplate.episodes.length > 0 && (
                    <div className="brief-subcard">
                      <strong>示范课程分集 ({currentTemplate.episodes.length} 讲/集)</strong>
                      {currentTemplate.episodes.map((ep, i) => (
                        <div key={i} className="ep-subrow">
                          <span>{ep.title}</span>
                          <small>包含完整口播讲稿与课件</small>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="brief-subcard">
                    <strong>示范课件与讲稿</strong>
                    {currentTemplate.assets.map((ast, i) => (
                      <div key={i} className="asset-subrow">
                        <span>{ast.originalName}</span>
                        <small>{ast.sizeText} · {ast.description}</small>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="modal-footer">
              <button
                type="button"
                className="secondary-button"
                onClick={() => {
                  handleFillTemplate(currentTemplate)
                  setDetailModalOpen(false)
                }}
              >
                <Wand2 size={15} /> 填入当前表单
              </button>
              <button
                type="button"
                className="primary-button highlight-sample-btn"
                disabled={busy}
                onClick={() => {
                  setDetailModalOpen(false)
                  handleCreateFromTemplate(currentTemplate)
                }}
              >
                <Sparkles size={15} /> 一键使用此示例创建课程
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
