/**
 * 项目工作台页面
 *
 * 完整的项目管理界面：
 * - 项目概览
 * - 分集内容列表
 * - 快速编辑和预览
 * - 批量导出
 * - 单集 Skills 配置
 */
import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import {
  Row,
  Col,
  Card,
  Table,
  Button,
  Space,
  Tag,
  Progress,
  Statistic,
  Timeline,
  message,
  Modal,
  Drawer,
  Alert,
  Dropdown,
  Badge,
  Empty,
  Spin,
  Typography
} from 'antd'
import {
  ArrowLeftOutlined,
  PlayCircleOutlined,
  EyeOutlined,
  EditOutlined,
  DownloadOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  SettingOutlined,
  RocketOutlined,
  ToolOutlined
} from '@ant-design/icons'

const { Text } = Typography

import { ContentEditor } from '@/components/ContentEditor'
import EpisodeSkillConfig from '@/components/EpisodeSkillConfig'
import { episodeContentService, EpisodeContent, ContentStatus, ExportFormat } from '@/services/episodeContentService'
import { projectService } from '@/services/projectService'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'

export const ProjectWorkspace: React.FC = () => {
  const navigate = useNavigate()
  const { projectId } = useParams<{ projectId: string }>()

  // 项目数据
  const [project, setProject] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  // 剧集内容
  const [contents, setContents] = useState<EpisodeContent[]>([])
  const [contentsLoading, setContentsLoading] = useState(false)

  // 内容编辑器
  const [editorVisible, setEditorVisible] = useState(false)
  const [selectedEpisode, setSelectedEpisode] = useState<number | null>(null)
  const [selectedContent, setSelectedContent] = useState<EpisodeContent | null>(null)

  // 批量操作
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])

  // Skills 配置
  const [skillConfigVisible, setSkillConfigVisible] = useState(false)
  const [selectedConfigEpisode, setSelectedConfigEpisode] = useState<number | null>(null)
  const [currentEpisodeConfig, setCurrentEpisodeConfig] = useState<any>(null)

  useEffect(() => {
    if (projectId) {
      loadProject()
      loadContents()
    }
  }, [projectId])

  const loadProject = async () => {
    if (!projectId) return

    setLoading(true)
    try {
      const data = await projectService.getProject(projectId)
      setProject(data)
    } catch (error) {
      message.error(`加载项目失败: ${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  const loadContents = async () => {
    if (!projectId) return

    setContentsLoading(true)
    try {
      const data = await episodeContentService.listContents(projectId)
      setContents(data)
    } catch (error) {
      console.error('加载内容失败:', error)
    } finally {
      setContentsLoading(false)
    }
  }

  // 打开内容编辑器
  const handleOpenContent = (episodeNumber: number, content?: EpisodeContent) => {
    setSelectedEpisode(episodeNumber)
    setSelectedContent(content || null)
    setEditorVisible(true)
  }

  // 打开 Skills 配置
  const handleOpenSkillConfig = async (episodeNumber: number) => {
    setSelectedConfigEpisode(episodeNumber)

    // 获取当前单集配置
    if (project?.episodeSkillOverrides?.[episodeNumber]) {
      setCurrentEpisodeConfig(project.episodeSkillOverrides[episodeNumber])
    } else {
      setCurrentEpisodeConfig(null)
    }

    setSkillConfigVisible(true)
  }

  const handleSaveSkillConfig = async (config: any) => {
    // 重新加载项目数据以获取最新配置
    await loadProject()
  }

  // 状态标签
  const getStatusTag = (status: ContentStatus) => {
    const config = {
      draft: { color: 'default', text: '草稿' },
      generating: { color: 'processing', text: '生成中' },
      pending_review: { color: 'warning', text: '待审核' },
      approved: { color: 'success', text: '已通过' },
      rejected: { color: 'error', text: '已拒绝' }
    }
    const { color, text } = config[status] || config.draft
    return <Tag color={color}>{text}</Tag>
  }

  // 导出菜单
  const exportMenu = {
    items: [
      { key: 'all', label: '导出全部内容' },
      { key: 'selected', label: '导出选中内容' },
      { type: 'divider' },
      { key: 'markdown', label: 'Markdown 格式' },
      { key: 'txt', label: '纯文本格式' },
      { key: 'pdf', label: 'PDF 格式' }
    ],
    onClick: async ({ key }: { key: string }) => {
      if (!projectId) return

      try {
        if (key === 'all' || key === 'selected') {
          const episodeNumbers = key === 'selected' && selectedRowKeys.length > 0
            ? selectedRowKeys.map(k => Number(k))
            : undefined

          const result = await episodeContentService.exportContents(projectId, {
            format: 'markdown',
            episode_numbers: episodeNumbers
          })

          if (result.content) {
            const blob = new Blob([result.content], { type: 'text/plain;charset=utf-8' })
            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            a.download = result.filename || `project_${projectId}_all.md`
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            URL.revokeObjectURL(url)

            message.success('导出成功')
          }
        }
      } catch (error) {
        message.error(`导出失败: ${(error as Error).message}`)
      }
    }
  }

  // 表格列定义
  const columns: ColumnsType<EpisodeContent> = [
    {
      title: '集数',
      dataIndex: 'episode_number',
      key: 'episode_number',
      width: 80,
      render: (num) => <Tag color="blue">#{num}</Tag>
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (title) => title || <span style={{ color: '#999' }}>(无标题)</span>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: ContentStatus) => getStatusTag(status)
    },
    {
      title: '质量分数',
      dataIndex: 'quality_score',
      key: 'quality_score',
      width: 120,
      render: (score) => (
        score !== null && score !== undefined ? (
          <Progress
            percent={score}
            size="small"
            status={score >= 80 ? 'success' : score >= 60 ? 'normal' : 'exception'}
          />
        ) : null
      )
    },
    {
      title: '字数',
      key: 'word_count',
      width: 100,
      render: (_, record) => {
        const count = record.content.length
        return <span>{count.toLocaleString()} 字</span>
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      width: 160,
      render: (date) => dayjs(date).format('MM-DD HH:mm')
    },
    {
      title: '操作',
      key: 'actions',
      width: 280,
      fixed: 'right' as const,
      render: (_, record) => {
        // 检查是否有自定义配置
        const hasCustomConfig = project?.episodeSkillOverrides?.[record.episode_number]
        const useDefault = !hasCustomConfig || hasCustomConfig.use_project_default

        return (
          <Space size="small">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleOpenContent(record.episode_number, record)}
            >
              预览
            </Button>
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleOpenContent(record.episode_number, record)}
            >
              编辑
            </Button>
            <Button
              type="link"
              size="small"
              icon={<ToolOutlined />}
              onClick={() => handleOpenSkillConfig(record.episode_number)}
              style={useDefault ? {} : { color: '#1677ff', fontWeight: 500 }}
            >
              配置 Skills
            </Button>
          </Space>
        )
      }
    }
  ]

  // 统计数据
  const getStatistics = () => {
    const total = contents.length
    const approved = contents.filter(c => c.status === 'approved').length
    const pending = contents.filter(c => c.status === 'pending_review').length
    const avgScore = contents.length > 0
      ? contents.reduce((sum, c) => sum + (c.quality_score || 0), 0) / contents.length
      : 0

    return { total, approved, pending, avgScore }
  }

  const stats = getStatistics()

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" tip="加载项目中..." />
      </div>
    )
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 头部 */}
      <Card
        title={
          <Space>
            <Button
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/projects')}
            >
              返回
            </Button>
            <span>{project?.name || '项目工作台'}</span>
            <Tag color="blue">ID: {projectId}</Tag>
          </Space>
        }
        extra={
          <Space>
            <Button icon={<SettingOutlined />}>设置</Button>
            <Dropdown menu={exportMenu}>
              <Button type="primary" icon={<DownloadOutlined />}>
                导出内容
              </Button>
            </Dropdown>
          </Space>
        }
      />

      {/* 统计概览 */}
      <Row gutter={16} style={{ marginTop: '16px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总集数"
              value={stats.total}
              prefix="#"
              suffix="集"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成"
              value={stats.approved}
              valueStyle={{ color: '#3f8600' }}
              suffix="集"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待审核"
              value={stats.pending}
              valueStyle={{ color: '#faad14' }}
              suffix="集"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均质量"
              value={stats.avgScore}
              precision={1}
              suffix="/ 100"
              valueStyle={{ color: stats.avgScore >= 80 ? '#3f8600' : '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主内容区域 */}
      <Row gutter={16} style={{ marginTop: '16px' }}>
        {/* 左侧：剧集列表 */}
        <Col span={16}>
          <Card
            title="剧集内容列表"
            extra={
              <Space>
                <Badge count={selectedRowKeys.length} offset={[10, 0]}>
                  <Button>批量操作</Button>
                </Badge>
                <Button
                  icon={<RocketOutlined />}
                  type="primary"
                  onClick={() => navigate(`/projects/${projectId}/execute`)}
                >
                  继续生成
                </Button>
              </Space>
            }
          >
            <Table
              columns={columns}
              dataSource={contents}
              rowKey="id"
              loading={contentsLoading}
              rowSelection={{
                selectedRowKeys,
                onChange: setSelectedRowKeys
              }}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 集`
              }}
              scroll={{ x: 1000 }}
            />
          </Card>
        </Col>

        {/* 右侧：项目信息 */}
        <Col span={8}>
          <Space direction="vertical" style={{ width: '100%' }} size="middle">
            {/* 项目信息 */}
            <Card title="项目信息" size="small">
              <Row gutter={[8, 8]}>
                <Col span={8}><span style={{ color: '#999' }}>总集数:</span></Col>
                <Col span={16}>{project?.totalEpisodes || '-'} 集</Col>

                <Col span={8}><span style={{ color: '#999' }}>进度:</span></Col>
                <Col span={16}>
                  <Progress
                    percent={Math.round((stats.approved / (project?.totalEpisodes || 1)) * 100)}
                    size="small"
                  />
                </Col>

                <Col span={8}><span style={{ color: '#999' }}>创建时间:</span></Col>
                <Col span={16}>{project?.createdAt ? dayjs(project.createdAt).format('YYYY-MM-DD') : '-'}</Col>

                <Col span={8}><span style={{ color: '#999' }}>Agent:</span></Col>
                <Col span={16}>{project?.agentId || '-'}</Col>
              </Row>
            </Card>

            {/* 使用的 Skills */}
            <Card title="使用的 Skills" size="small">
              {project?.skillSettings && Object.keys(project.skillSettings).length > 0 ? (
                <Space direction="vertical" style={{ width: '100%' }} size="small">
                  {Object.entries(project.skillSettings).map(([skillId, config]: [string, any]) => (
                    <Tag key={skillId} color={config?.enabled ? 'green' : 'default'}>
                      {skillId}
                    </Tag>
                  ))}
                </Space>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未配置 Skills" />
              )}
            </Card>

            {/* 最近活动 */}
            <Card title="最近活动" size="small">
              <Timeline
                items={contents.slice(-5).reverse().map((c) => ({
                  color: c.status === 'approved' ? 'green' : 'blue',
                  children: (
                    <Space direction="vertical" size={0}>
                      <Text>第 {c.episode_number} 集 {c.status === 'approved' ? '完成' : '更新'}</Text>
                      <span style={{ fontSize: '12px', color: '#999' }}>
                        {dayjs(c.updated_at).format('MM-DD HH:mm')}
                      </span>
                    </Space>
                  )
                }))}
              />
              {contents.length === 0 && (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无活动" />
              )}
            </Card>
          </Space>
        </Col>
      </Row>

      {/* 内容编辑器 */}
      <ContentEditor
        visible={editorVisible}
        projectId={projectId || ''}
        episodeNumber={selectedEpisode || undefined}
        content={selectedContent || undefined}
        onClose={() => {
          setEditorVisible(false)
          setSelectedEpisode(null)
          setSelectedContent(null)
        }}
        onSave={loadContents}
      />

      {/* Skills 配置 */}
      {projectId && selectedConfigEpisode && (
        <EpisodeSkillConfig
          visible={skillConfigVisible}
          projectId={projectId}
          episodeNumber={selectedConfigEpisode}
          currentConfig={currentEpisodeConfig}
          onSave={handleSaveSkillConfig}
          onClose={() => {
            setSkillConfigVisible(false)
            setSelectedConfigEpisode(null)
            setCurrentEpisodeConfig(null)
          }}
        />
      )}
    </div>
  )
}
