/**
 * Memory System Page
 * Tabbed interface for managing story memory elements
 */
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import {
  Tabs,
  Timeline,
  Card,
  Tag,
  Badge,
  Modal,
  Form,
  Button,
  Select,
  Input,
  Space,
  Statistic,
  Row,
  Col,
  Avatar,
  Divider,
  Empty,
  Spin,
  message,
  Progress,
  Alert
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckOutlined,
  ClockCircleOutlined,
  UserOutlined,
  ReloadOutlined
} from '@ant-design/icons'
import { useMemoryStore } from '@/stores/memoryStore'
import { ImportanceLevel } from '@/services/memoryService'

const { TabPane } = Tabs
const { TextArea } = Input

interface MemorySystemProps {
  projectId?: string
}

const MemorySystem: React.FC<MemorySystemProps> = ({ projectId: propProjectId }) => {
  const { id: routeProjectId } = useParams<{ id: string }>()
  const projectId = propProjectId || routeProjectId
  const {
    memorySystem,
    timeline,
    threads,
    characterStates,
    foreshadowing,
    relationships,
    loading,
    error,
    fetchMemorySystem,
    createThread,
    updateThread,
    deleteThread,
    resolveThread,
    createForeshadowing,
    updateForeshadowing,
    deleteForeshadowing,
    timelineFilters,
    setTimelineFilters,
    clearTimelineFilters
  } = useMemoryStore()

  const [activeTab, setActiveTab] = useState('timeline')
  const [threadModalVisible, setThreadModalVisible] = useState(false)
  const [foreshadowingModalVisible, setForeshadowingModalVisible] = useState(false)
  const [editingThread, setEditingThread] = useState<any>(null)
  const [editingForeshadowing, setEditingForeshadowing] = useState<any>(null)
  const [threadForm] = Form.useForm()
  const [foreshadowingForm] = Form.useForm()

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

  const getImportanceColor = (importance: ImportanceLevel) => {
    switch (importance) {
      case 'high': return 'red'
      case 'medium': return 'orange'
      case 'low': return 'blue'
      default: return 'default'
    }
  }

  const getImportanceTag = (importance: ImportanceLevel) => {
    const labels = { high: '高', medium: '中', low: '低' }
    return <Tag color={getImportanceColor(importance)}>{labels[importance]}</Tag>
  }

  const getStatusTag = (status: string) => {
    const statusConfig: Record<string, { color: string; label: string }> = {
      pending: { color: 'default', label: '待处理' },
      in_progress: { color: 'processing', label: '进行中' },
      resolved: { color: 'success', label: '已解决' },
      planted: { color: 'blue', label: '已埋伏笔' },
      partially_paid: { color: 'orange', label: '部分收线' },
      paid_off: { color: 'green', label: '已收线' }
    }
    const config = statusConfig[status] || { color: 'default', label: status }
    return <Tag color={config.color}>{config.label}</Tag>
  }

  const handleCreateThread = async (values: any) => {
    if (!projectId) return
    try {
      await createThread(projectId, values)
      message.success('剧情线创建成功')
      setThreadModalVisible(false)
      threadForm.resetFields()
      setEditingThread(null)
    } catch (error) {
      message.error('创建失败')
    }
  }

  const handleUpdateThread = async (values: any) => {
    if (!projectId || !editingThread) return
    try {
      await updateThread(projectId, editingThread.id, values)
      message.success('剧情线更新成功')
      setThreadModalVisible(false)
      threadForm.resetFields()
      setEditingThread(null)
    } catch (error) {
      message.error('更新失败')
    }
  }

  const handleDeleteThread = async (threadId: string) => {
    if (!projectId) return
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条剧情线吗？',
      onOk: async () => {
        try {
          await deleteThread(projectId, threadId)
          message.success('删除成功')
        } catch (error) {
          message.error('删除失败')
        }
      }
    })
  }

  const handleResolveThread = async (threadId: string) => {
    if (!projectId) return
    try {
      await resolveThread(projectId, threadId)
      message.success('剧情线已标记为已解决')
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleEditThread = (thread: any) => {
    setEditingThread(thread)
    threadForm.setFieldsValue(thread)
    setThreadModalVisible(true)
  }

  const handleCreateForeshadowing = async (values: any) => {
    if (!projectId) return
    try {
      await createForeshadowing(projectId, values)
      message.success('伏笔创建成功')
      setForeshadowingModalVisible(false)
      foreshadowingForm.resetFields()
      setEditingForeshadowing(null)
    } catch (error) {
      message.error('创建失败')
    }
  }

  const handleEditForeshadowing = (item: any) => {
    setEditingForeshadowing(item)
    foreshadowingForm.setFieldsValue(item)
    setForeshadowingModalVisible(true)
  }

  const handleUpdateForeshadowing = async (values: any) => {
    if (!projectId || !editingForeshadowing) return
    try {
      await updateForeshadowing(projectId, editingForeshadowing.id, values)
      message.success('伏笔更新成功')
      setForeshadowingModalVisible(false)
      foreshadowingForm.resetFields()
      setEditingForeshadowing(null)
    } catch (error) {
      message.error('更新失败')
    }
  }

  const handleDeleteForeshadowing = async (itemId: string) => {
    if (!projectId) return
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条伏笔吗？',
      onOk: async () => {
        try {
          await deleteForeshadowing(projectId, itemId)
          message.success('删除成功')
        } catch (error) {
          message.error('删除失败')
        }
      }
    })
  }

  if (loading && !memorySystem) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" tip="正在加载记忆系统..." />
      </div>
    )
  }

  if (error) {
    return (
      <div style={{ padding: '24px' }}>
        <Card>
          <Alert
            message="加载失败"
            description={error}
            type="error"
            showIcon
            action={
              <Button size="small" onClick={() => projectId && fetchMemorySystem(projectId)}>
                重试
              </Button>
            }
          />
        </Card>
      </div>
    )
  }

  if (!memorySystem) {
    return (
      <div style={{ padding: '24px' }}>
        <Card>
          <Empty
            description="暂无记忆系统数据"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Button type="primary" onClick={() => projectId && fetchMemorySystem(projectId)}>
              刷新
            </Button>
          </Empty>
        </Card>
      </div>
    )
  }

  // Statistics Overview
  const renderStatistics = () => {
    const stats = memorySystem?.statistics
    const titleStyle = { fontSize: '12px', color: '#8c8c8c' }
    const valueStyle = { fontSize: '18px', fontWeight: 600 }
    const iconStyle = { fontSize: '14px' }

    return (
      <Row gutter={12} style={{ marginBottom: 20 }}>
        <Col flex={1}>
          <Card size="small" bodyStyle={{ padding: '12px' }}>
            <Statistic 
              title={<span style={titleStyle}>总事件</span>} 
              value={stats?.totalEvents || 0} 
              prefix={<ClockCircleOutlined style={iconStyle} />}
              valueStyle={valueStyle}
            />
          </Card>
        </Col>
        <Col flex={1}>
          <Card size="small" bodyStyle={{ padding: '12px' }}>
            <Statistic
              title={<span style={titleStyle}>剧情线</span>}
              value={stats?.totalThreads || 0}
              suffix={<span style={{ fontSize: '12px', color: '#bfbfbf', fontWeight: 'normal' }}>/ {stats?.resolvedThreads || 0} 已解决</span>}
              valueStyle={valueStyle}
            />
          </Card>
        </Col>
        <Col flex={1}>
          <Card size="small" bodyStyle={{ padding: '12px' }}>
            <Statistic 
              title={<span style={titleStyle}>角色</span>} 
              value={stats?.totalCharacters || 0} 
              prefix={<UserOutlined style={iconStyle} />}
              valueStyle={valueStyle}
            />
          </Card>
        </Col>
        <Col flex={1}>
          <Card size="small" bodyStyle={{ padding: '12px' }}>
            <Statistic
              title={<span style={titleStyle}>伏笔</span>}
              value={stats?.totalForeshadowing || 0}
              suffix={<span style={{ fontSize: '12px', color: '#bfbfbf', fontWeight: 'normal' }}>/ {stats?.paidOffForeshadowing || 0} 已收线</span>}
              valueStyle={valueStyle}
            />
          </Card>
        </Col>
        <Col flex={1}>
          <Card size="small" bodyStyle={{ padding: '12px' }}>
            <Statistic 
              title={<span style={titleStyle}>关系</span>} 
              value={stats?.totalRelationships || 0} 
              valueStyle={valueStyle}
            />
          </Card>
        </Col>
      </Row>
    )
  }

  // Timeline Tab
  const renderTimeline = () => (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Select
          placeholder="筛选角色"
          allowClear
          style={{ width: 150 }}
          onChange={(value) => setTimelineFilters({ ...timelineFilters, character: value })}
          value={timelineFilters.character}
        >
          {(Array.isArray(characterStates) ? characterStates : []).map(cs => (
            <Select.Option key={cs.characterName} value={cs.characterName}>
              {cs.characterName}
            </Select.Option>
          ))}
        </Select>
        <Select
          placeholder="筛选集数"
          allowClear
          style={{ width: 120 }}
          onChange={(value) => setTimelineFilters({ ...timelineFilters, episode: value })}
          value={timelineFilters.episode}
        >
          {Array.from(new Set((Array.isArray(timeline) ? timeline : []).map(t => t.episodeNumber))).map(ep => (
            <Select.Option key={ep} value={ep}>第 {ep} 集</Select.Option>
          ))}
        </Select>
        <Select
          placeholder="筛选重要性"
          allowClear
          style={{ width: 120 }}
          onChange={(value) => setTimelineFilters({ ...timelineFilters, importance: value })}
          value={timelineFilters.importance}
        >
          <Select.Option value="high">高</Select.Option>
          <Select.Option value="medium">中</Select.Option>
          <Select.Option value="low">低</Select.Option>
        </Select>
        <Button onClick={clearTimelineFilters}>清除筛选</Button>
      </Space>

      {(Array.isArray(timeline) ? timeline : []).length === 0 ? (
        <Empty description="暂无时间线事件" />
      ) : (
        <Timeline mode="left">
          {(Array.isArray(timeline) ? timeline : []).map(event => (
            <Timeline.Item
              key={event.id}
              dot={<Avatar size="small" icon={<ClockCircleOutlined />} />}
              color={getImportanceColor(event.importance)}
            >
              <Card size="small" style={{ marginBottom: 8 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <Tag color="blue">第 {event.episodeNumber} 集</Tag>
                    {getImportanceTag(event.importance)}
                    <Tag>{event.category}</Tag>
                  </Space>
                  <div>{event.description}</div>
                  <Space wrap>
                    {event.characters.map(char => (
                      <Tag key={char} color="geekblue">{char}</Tag>
                    ))}
                  </Space>
                </Space>
              </Card>
            </Timeline.Item>
          ))}
        </Timeline>
      )}
    </div>
  )

  // Pending Threads Tab
  const renderThreads = () => (
    <div>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => {
          setEditingThread(null)
          threadForm.resetFields()
          setThreadModalVisible(true)
        }}
        style={{ marginBottom: 16 }}
      >
        添加剧情线
      </Button>

      {(Array.isArray(threads) ? threads : []).length === 0 ? (
        <Empty description="暂无待处理剧情线" />
      ) : (
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {(Array.isArray(threads) ? threads : []).map(thread => (
            <Card
              key={thread.id}
              size="small"
              extra={
                <Space>
                  <Button
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => handleEditThread(thread)}
                  >
                    编辑
                  </Button>
                  {thread.status !== 'resolved' && (
                    <Button
                      size="small"
                      type="primary"
                      icon={<CheckOutlined />}
                      onClick={() => handleResolveThread(thread.id)}
                    >
                      标记解决
                    </Button>
                  )}
                  <Button
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleDeleteThread(thread.id)}
                  >
                    删除
                  </Button>
                </Space>
              }
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                <Space>
                  {getImportanceTag(thread.importance)}
                  {getStatusTag(thread.status)}
                </Space>
                <div>{thread.description}</div>
                {thread.reminderEpisode && (
                  <Tag color="purple">提醒: 第 {thread.reminderEpisode} 集</Tag>
                )}
                {thread.relatedCharacters && thread.relatedCharacters.length > 0 && (
                  <Space wrap>
                    {thread.relatedCharacters.map(char => (
                      <Tag key={char} color="geekblue">{char}</Tag>
                    ))}
                  </Space>
                )}
              </Space>
            </Card>
          ))}
        </Space>
      )}
    </div>
  )

  // Character States Tab
  const renderCharacterStates = () => (
    <div>
      {(Array.isArray(characterStates) ? characterStates : []).length === 0 ? (
        <Empty description="暂无角色状态信息" />
      ) : (
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          {(Array.isArray(characterStates) ? characterStates : []).map(cs => (
            <Card
              key={cs.characterName}
              title={
                <Space>
                  <Avatar size="small" icon={<UserOutlined />} />
                  {cs.characterName}
                </Space>
              }
            >
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <div>
                  <strong>当前状态: </strong>
                  {cs.currentState}
                </div>
                <Divider orientation="left" style={{ fontSize: 12, margin: '8px 0' }}>状态历史</Divider>
                <Timeline mode="left">
                  {cs.history.map((entry, idx) => (
                    <Timeline.Item key={idx}>
                      <Tag color="blue">第 {entry.episodeNumber} 集</Tag>
                      {entry.state}
                    </Timeline.Item>
                  ))}
                </Timeline>
              </Space>
            </Card>
          ))}
        </Space>
      )}
    </div>
  )

  // Foreshadowing Tab
  const renderForeshadowing = () => (
    <div>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => {
          setEditingForeshadowing(null)
          foreshadowingForm.resetFields()
          setForeshadowingModalVisible(true)
        }}
        style={{ marginBottom: 16 }}
      >
        添加伏笔
      </Button>

      {(Array.isArray(foreshadowing) ? foreshadowing : []).length === 0 ? (
        <Empty description="暂无伏笔记录" />
      ) : (
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {(Array.isArray(foreshadowing) ? foreshadowing : []).map(item => (
            <Card
              key={item.id}
              size="small"
              extra={
                <Space>
                  <Button
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => handleEditForeshadowing(item)}
                  >
                    编辑
                  </Button>
                  <Button
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleDeleteForeshadowing(item.id)}
                  >
                    删除
                  </Button>
                </Space>
              }
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                <Space>
                  {getImportanceTag(item.importance)}
                  {getStatusTag(item.status)}
                  <Tag color="blue">埋于第 {item.plantedEpisode} 集</Tag>
                  {item.payoffEpisode && (
                    <Tag color="green">收于第 {item.payoffEpisode} 集</Tag>
                  )}
                </Space>
                <div>{item.description}</div>
              </Space>
            </Card>
          ))}
        </Space>
      )}
    </div>
  )

  // Relationships Tab
  const renderRelationships = () => (
    <div>
      {(Array.isArray(relationships) ? relationships : []).length === 0 ? (
        <Empty description="暂无关系数据" />
      ) : (
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {(Array.isArray(relationships) ? relationships : []).map((rel, idx) => (
            <Card key={idx} size="small">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Space>
                  <Tag color="geekblue">{rel.sourceCharacter}</Tag>
                  <span>→</span>
                  <Tag color="geekblue">{rel.targetCharacter}</Tag>
                  <Tag color={rel.strength > 70 ? 'red' : rel.strength > 40 ? 'orange' : 'blue'}>
                    {rel.relationType}
                  </Tag>
                  <Progress percent={rel.strength} size="small" style={{ width: 100 }} />
                </Space>
                {rel.description && <div>{rel.description}</div>}
                {rel.evolutionHistory && rel.evolutionHistory.length > 0 && (
                  <div style={{ fontSize: 12, color: '#888' }}>
                    关系演变: {rel.evolutionHistory.map(e => `第${e.episodeNumber}集`).join(', ')}
                  </div>
                )}
              </Space>
            </Card>
          ))}
        </Space>
      )}
    </div>
  )

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ flexShrink: 0 }}>
        {renderStatistics()}
      </div>

      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab} 
        type="card"
        style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}
        tabBarExtraContent={
          <Button 
            type="text" 
            size="small"
            icon={<ReloadOutlined spin={loading} />} 
            onClick={() => projectId && fetchMemorySystem(projectId)}
            loading={loading}
          >
            刷新数据
          </Button>
        }
      >
        <TabPane tab="时间线" key="timeline">
          <div style={{ padding: '16px 0 24px 0', height: '100%', overflowY: 'auto' }}>
            {renderTimeline()}
          </div>
        </TabPane>
        <TabPane
          tab={
            <span>
              剧情线
              <Badge count={threads.filter(t => t.status !== 'resolved').length} style={{ marginLeft: 8 }} />
            </span>
          }
          key="threads"
        >
          <div style={{ padding: '16px 0 24px 0', height: '100%', overflowY: 'auto' }}>
            {renderThreads()}
          </div>
        </TabPane>
        <TabPane tab="角色状态" key="characters">
          <div style={{ padding: '16px 0 24px 0', height: '100%', overflowY: 'auto' }}>
            {renderCharacterStates()}
          </div>
        </TabPane>
        <TabPane tab="伏笔管理" key="foreshadowing">
          <div style={{ padding: '16px 0 24px 0', height: '100%', overflowY: 'auto' }}>
            {renderForeshadowing()}
          </div>
        </TabPane>
        <TabPane tab="关系图" key="relationships">
          <div style={{ padding: '16px 0 24px 0', height: '100%', overflowY: 'auto' }}>
            {renderRelationships()}
          </div>
        </TabPane>
      </Tabs>

      {/* Thread Modal */}
      <Modal
        title={editingThread ? '编辑剧情线' : '添加剧情线'}
        open={threadModalVisible}
        onCancel={() => {
          setThreadModalVisible(false)
          setEditingThread(null)
          threadForm.resetFields()
        }}
        footer={null}
      >
        <Form
          form={threadForm}
          layout="vertical"
          onFinish={editingThread ? handleUpdateThread : handleCreateThread}
        >
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea rows={4} placeholder="描述这条剧情线..." />
          </Form.Item>
          <Form.Item
            name="importance"
            label="重要性"
            rules={[{ required: true }]}
            initialValue="medium"
          >
            <Select>
              <Select.Option value="high">高</Select.Option>
              <Select.Option value="medium">中</Select.Option>
              <Select.Option value="low">低</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="reminderEpisode" label="提醒集数">
            <Input type="number" placeholder="在指定集数提醒处理" />
          </Form.Item>
          <Form.Item name="relatedCharacters" label="相关角色">
            <Select mode="tags" placeholder="选择或输入角色名">
              {(Array.isArray(characterStates) ? characterStates : []).map(cs => (
                <Select.Option key={cs.characterName} value={cs.characterName}>
                  {cs.characterName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态" initialValue="pending">
            <Select>
              <Select.Option value="pending">待处理</Select.Option>
              <Select.Option value="in_progress">进行中</Select.Option>
              <Select.Option value="resolved">已解决</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingThread ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setThreadModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* Foreshadowing Modal */}
      <Modal
        title={editingForeshadowing ? '编辑伏笔' : '添加伏笔'}
        open={foreshadowingModalVisible}
        onCancel={() => {
          setForeshadowingModalVisible(false)
          setEditingForeshadowing(null)
          foreshadowingForm.resetFields()
        }}
        footer={null}
      >
        <Form
          form={foreshadowingForm}
          layout="vertical"
          onFinish={editingForeshadowing ? handleUpdateForeshadowing : handleCreateForeshadowing}
        >
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea rows={4} placeholder="描述这个伏笔..." />
          </Form.Item>
          <Form.Item
            name="importance"
            label="重要性"
            rules={[{ required: true }]}
            initialValue="medium"
          >
            <Select>
              <Select.Option value="high">高</Select.Option>
              <Select.Option value="medium">中</Select.Option>
              <Select.Option value="low">低</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="plantedEpisode"
            label="埋伏笔集数"
            rules={[{ required: true }]}
          >
            <Input type="number" placeholder="在第几集埋下伏笔" />
          </Form.Item>
          {editingForeshadowing && (
            <>
              <Form.Item name="status" label="状态">
                <Select>
                  <Select.Option value="planted">已埋伏笔</Select.Option>
                  <Select.Option value="partially_paid">部分收线</Select.Option>
                  <Select.Option value="paid_off">已收线</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item name="payoffEpisode" label="收线集数">
                <Input type="number" placeholder="在第几集收线" />
              </Form.Item>
            </>
          )}
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingForeshadowing ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setForeshadowingModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default MemorySystem
