import { useEffect, useState } from 'react'
import { Card, List, Tag, Space, Button, Typography, Progress, Empty, Spin, Badge, Tooltip, message, Segmented } from 'antd'
import { PlayCircleOutlined, CheckCircleOutlined, ClockCircleOutlined, EditOutlined, EyeOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import { useProjectStore } from '@/stores/projectStore'
import { Episode } from '@/services/projectService'

const { Text } = Typography

type EpisodeStatusFilter = 'all' | 'pending' | 'writing' | 'completed'

interface EpisodeSidebarProps {
  projectId: string;
  onEpisodeSelect?: (episode: Episode) => void;
  currentEpisodeId?: string;
  onSendMessage?: (msg: string) => void;
}

export const EpisodeSidebar: React.FC<EpisodeSidebarProps> = ({
  projectId,
  onEpisodeSelect,
  currentEpisodeId,
  onSendMessage
}) => {
  const { episodes, loading, fetchEpisodes, executeEpisode } = useProjectStore()
  const [executing, setExecuting] = useState<number | null>(null)
  const [statusFilter, setStatusFilter] = useState<EpisodeStatusFilter>('all')

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

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'pending': 'default',
      'writing': 'processing',
      'completed': 'success',
      'needs-review': 'warning'
    }
    return colors[status] || 'default'
  }

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      'pending': '待创作',
      'draft': '草稿',
      'writing': '制作中',
      'completed': '已完成',
      'needs-review': '需审核'
    }
    return texts[status] || status
  }

  const getStatusIcon = (status: string) => {
    const icons: Record<string, React.ReactNode> = {
      'pending': <ClockCircleOutlined />,
      'writing': <ReloadOutlined spin />,
      'completed': <CheckCircleOutlined />,
      'needs-review': <EditOutlined />
    }
    return icons[status] || <ClockCircleOutlined />
  }

  const handleExecuteEpisode = async (episodeNum: number) => {
    if (!projectId) return

    setExecuting(episodeNum)
    try {
      // 通过 WebSocket 发送创作请求，让 DirectorAgent 处理
      if (onSendMessage) {
        onSendMessage(`开始创作第 ${episodeNum} 集`)
        message.info(`正在处理创作请求：第 ${episodeNum} 集`)
      } else {
        // 降级方案：如果 WebSocket 不可用，使用原有的 API 方式
        await executeEpisode(projectId, episodeNum)
        message.success(`EP${episodeNum} 创作完成！`)
        await fetchEpisodes(projectId)
      }
    } catch (error) {
      message.error(`创作失败: ${(error as Error).message}`)
    } finally {
      // 延迟重置执行状态，给用户一些视觉反馈
      setTimeout(() => {
        if (executing === episodeNum) {
          setExecuting(null)
        }
      }, 1000)
    }
  }

  const totalEpisodes = episodes.length
  const completedEpisodes = episodes.filter(ep => ep.status === 'completed').length
  const progress = totalEpisodes > 0 ? Math.round((completedEpisodes / totalEpisodes) * 100) : 0

  // 根据筛选状态过滤剧集
  const filteredEpisodes = episodes.filter(episode => {
    if (statusFilter === 'all') return true
    if (statusFilter === 'pending') return episode.status === 'pending'
    if (statusFilter === 'writing') return episode.status === 'draft' || episode.status === 'writing'
    if (statusFilter === 'completed') return episode.status === 'completed'
    return true
  })

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        background: '#fafafa',
        borderRight: '1px solid #f0f0f0',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden'
      }}
    >
      {/* 头部：进度统计 */}
      <div style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0' }}>
        <Space direction="vertical" style={{ width: '100%' }} size="small">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text strong style={{ fontSize: '14px' }}>剧集管理</Text>
            <Badge count={completedEpisodes} style={{ backgroundColor: '#52c41a' }} />
          </div>
          <Progress
            percent={progress}
            size="small"
            status={progress === 100 ? 'success' : 'active'}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
          <Text type="secondary" style={{ fontSize: '12px' }}>
            已完成 {completedEpisodes} / {totalEpisodes} 集
          </Text>
        </Space>
      </div>

      {/* 状态筛选器 - 响应式处理 */}
      <div style={{ padding: '8px 12px', borderBottom: '1px solid #f0f0f0', overflowX: 'hidden' }}>
        <Segmented
          value={statusFilter}
          onChange={setStatusFilter}
          size="middle"
          block
          options={[
            { label: `全部${totalEpisodes}`, value: 'all' },
            { label: `待创作${episodes.filter(ep => ep.status === 'pending').length}`, value: 'pending' },
            { label: `创作中${episodes.filter(ep => ep.status === 'draft' || ep.status === 'writing').length}`, value: 'writing' },
            { label: `已完成${completedEpisodes}`, value: 'completed' }
          ]}
          style={{ fontSize: '12px', whiteSpace: 'nowrap' }}
        />
      </div>

      {/* 剧集列表 */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: '20px' }}>
            <Spin tip="加载中..." />
          </div>
        ) : filteredEpisodes.length === 0 ? (
          <Empty
            description="暂无剧集"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ marginTop: '20px' }}
          />
        ) : (
          <Space direction="vertical" style={{ width: '100%' }} size="small">
            {filteredEpisodes.map((episode) => (
              <Card
                key={episode.id}
                size="small"
                style={{
                  cursor: 'pointer',
                  border: currentEpisodeId === episode.id ? '2px solid #1677ff' : '1px solid #f0f0f0',
                  background: currentEpisodeId === episode.id ? '#f0f5ff' : '#fff'
                }}
                onClick={() => onEpisodeSelect?.(episode)}
                hoverable
              >
                <Space direction="vertical" style={{ width: '100%' }} size="small">
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Space>
                      <Text strong style={{ fontSize: '14px' }}>
                        EP{String(episode.number).padStart(2, '0')}
                      </Text>
                      {episode.title && (
                        <Text style={{ fontSize: '13px', color: '#666' }} ellipsis>
                          {episode.title}
                        </Text>
                      )}
                    </Space>
                    <Tag
                      color={getStatusColor(episode.status)}
                      icon={getStatusIcon(episode.status)}
                      style={{ margin: 0, fontSize: '12px' }}
                    >
                      {getStatusText(episode.status)}
                    </Tag>
                  </div>

                  {episode.qualityScore && (
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#999' }}>
                      <span>质量: {episode.qualityScore}</span>
                      {episode.issues && episode.issues.length > 0 && (
                        <span>问题: {episode.issues.length}</span>
                      )}
                    </div>
                  )}

                  {episode.status === 'pending' && (
                    <Button
                      type="primary"
                      size="small"
                      icon={<PlayCircleOutlined />}
                      onClick={(e) => {
                        e.stopPropagation()
                        handleExecuteEpisode(episode.number)
                      }}
                      loading={executing === episode.number}
                      style={{ width: '100%' }}
                    >
                      开始创作
                    </Button>
                  )}

                  {episode.status === 'completed' && (
                    <Button
                      size="small"
                      icon={<EyeOutlined />}
                      onClick={(e) => {
                        e.stopPropagation()
                        onEpisodeSelect?.(episode)
                      }}
                      style={{ width: '100%' }}
                    >
                      查看内容
                    </Button>
                  )}
                </Space>
              </Card>
            ))}
          </Space>
        )}
      </div>
    </div>
  )
}
