import React, { useState } from 'react';
import { Card, Typography, Space, Tabs, List, Button, Empty, Timeline, Badge } from 'antd';
import {
  BookOutlined,
  UserOutlined,
  EnvironmentOutlined,
  HistoryOutlined,
  BulbOutlined,
  EditOutlined,
  ClockCircleOutlined,
  AlertOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;

interface ContextPanelProps {
  project: any;
  loading: boolean;
  activeStates?: any[];
  memoryItems?: any[];
  width?: number;
  onUpdateContext?: (type: string, data: any) => void;
  onNavigateToSettings?: () => void;
}

export const ContextPanel: React.FC<ContextPanelProps> = ({
  project,
  loading,
  activeStates = [],
  memoryItems = [],
  width = 350,
  onNavigateToSettings
}) => {
  const [activeTab, setActiveTab] = useState('world');

  // 模拟数据 - 实际应从 project.globalContext 获取
  const worldSetting = project?.globalContext?.worldSetting || "暂无世界观设定";
  const overallOutline = project?.globalContext?.overallOutline || "暂无整体大纲设定";
  const rawCharacters = project?.globalContext?.characterProfiles;
  // 人物设定可能存储在 characterProfiles (对象) 或 styleGuide (文本字符串)
  const characters = (rawCharacters && typeof rawCharacters === 'object') ? rawCharacters : {};
  const charactersText = project?.globalContext?.styleGuide || "";

  // Use passed activeStates or default if empty (and not loading)
  const displayStates = activeStates.length > 0 ? activeStates : [
    { type: 'time', value: '未初始化' },
    { type: 'location', value: '未初始化' }
  ];

  // 渲染内容
  const renderContent = () => (
    <div style={{ width: '100%', minWidth: 0, overflow: 'hidden' }}>
      <Title level={4} style={{ width: '100%', minWidth: 0 }}>
        <BookOutlined /> 故事上下文
      </Title>

      {/* 动态状态卡片 */}
      <Card
        size="small"
        title="当前状态 (Active State)"
        style={{ marginBottom: '16px', background: '#f6ffed', borderColor: '#b7eb8f', width: '100%', minWidth: 0 }}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {displayStates.map((state, idx) => (
            <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', minWidth: 0, gap: '8px' }}>
              <Text type="secondary" style={{ flexShrink: 0 }}>{state.type === 'time' ? <HistoryOutlined /> : state.type === 'location' ? <EnvironmentOutlined /> : <UserOutlined />}</Text>
              <Text strong style={{ textAlign: 'right', flex: 1, wordBreak: 'break-word' }}>{state.value}</Text>
            </div>
          ))}
        </Space>
      </Card>

      <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ width: '100%', minWidth: 0 }}
        items={[
          {
            key: 'world',
            label: '世界观',
            children: (
              <div style={{ width: '100%', minWidth: 0 }}>
                <Paragraph ellipsis={{ rows: 6, expandable: true, symbol: '展开' }}>
                  {worldSetting}
                </Paragraph>
                <Button
                  type="dashed"
                  block
                  icon={<EditOutlined />}
                  onClick={onNavigateToSettings}
                >
                  更新设定
                </Button>
              </div>
            ),
          },
          {
            key: 'characters',
            label: '人物',
            children: (
              <div style={{ width: '100%', minWidth: 0 }}>
                {/* 如果有文本格式的人物设定，优先显示 */}
                {charactersText ? (
                  <Paragraph
                    ellipsis={{ rows: 10, expandable: true, symbol: '展开' }}
                    style={{ fontSize: '12px', whiteSpace: 'pre-wrap' }}
                  >
                    {charactersText}
                  </Paragraph>
                ) : Object.keys(characters).length > 0 ? (
                  <List
                    dataSource={Object.entries(characters)}
                    renderItem={([name, profile]: [string, any]) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={<UserOutlined style={{ fontSize: '24px', color: '#1890ff' }} />}
                          title={<span style={{ wordBreak: 'break-word' }}>{name}</span>}
                          description={<Text ellipsis={{ tooltip: profile }} style={{ wordBreak: 'break-word' }}>{profile}</Text>}
                        />
                      </List.Item>
                    )}
                  />
                ) : (
                  <Empty description="暂无人物设定" image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
                <Button
                  type="dashed"
                  block
                  icon={<EditOutlined />}
                  style={{ marginTop: '8px' }}
                  onClick={onNavigateToSettings}
                >
                  更新设定
                </Button>
              </div>
            ),
          },
          {
            key: 'outline',
            label: '大纲',
            children: (
              <div style={{ width: '100%', minWidth: 0 }}>
                <Paragraph ellipsis={{ rows: 10, expandable: true, symbol: '展开' }} style={{ whiteSpace: 'pre-wrap' }}>
                  {overallOutline}
                </Paragraph>
                <Button
                  type="dashed"
                  block
                  icon={<EditOutlined />}
                  style={{ marginTop: '8px' }}
                  onClick={onNavigateToSettings}
                >
                  更新设定
                </Button>
              </div>
            ),
          },
          {
            key: 'memory',
            label: '记忆库',
            children: memoryItems.length > 0 ? (
              <MemoryLibrary items={memoryItems} />
            ) : (
              <EmptyMemoryState />
            ),
          },
        ]}
      />
    </div>
  );

  // 使用统一的布局模式（移除 Sider 组件，改用普通 div）
  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        background: '#fff',
        overflow: 'hidden',
        minWidth: 0
      }}
    >
      <div style={{ padding: '16px', flex: 1, overflowY: 'auto', minWidth: 0 }}>
        {renderContent()}
      </div>
    </div>
  );
};

// 记忆库组件
const MemoryLibrary: React.FC<{ items: any[] }> = ({ items }) => {
  // 按类型分组记忆项
  const timelineItems = items.filter((item: any) => item.type === 'timeline');
  const characterStates = items.filter((item: any) => item.type === 'character_state');
  const pendingThreads = items.filter((item: any) => item.type === 'pending_thread');
  const foreshadowing = items.filter((item: any) => item.type === 'foreshadowing');

  // 构建 tabs items
  const tabItems = [
    {
      key: 'all',
      label: `全部 (${items.length})`,
      children: (
        <Timeline
          mode="left"
          items={items.map((item: any, idx: number) => ({
            color: getMemoryColor(item.type),
            dot: getMemoryIcon(item.type),
            children: (
              <div key={idx}>
                <Text strong style={{ fontSize: '12px' }}>{item.title || item.type}</Text>
                <br />
                <Text style={{ fontSize: '12px', color: '#666' }}>{item.description}</Text>
                {item.timestamp && (
                  <Text type="secondary" style={{ fontSize: '11px', display: 'block', marginTop: '4px' }}>
                    <ClockCircleOutlined /> {new Date(item.timestamp).toLocaleTimeString()}
                  </Text>
                )}
              </div>
            )
          }))}
        />
      )
    }
  ];

  if (timelineItems.length > 0) {
    tabItems.push({
      key: 'timeline',
      label: `时间线 (${timelineItems.length})`,
      children: (
        <List
          size="small"
          dataSource={timelineItems}
          renderItem={(item: any) => (
            <List.Item>
              <List.Item.Meta
                title={<Text style={{ fontSize: '13px' }}>{item.title}</Text>}
                description={<Text style={{ fontSize: '12px' }}>{item.description}</Text>}
              />
            </List.Item>
          )}
        />
      )
    });
  }

  if (characterStates.length > 0) {
    tabItems.push({
      key: 'character',
      label: `角色 (${characterStates.length})`,
      children: (
        <List
          size="small"
          dataSource={characterStates}
          renderItem={(item: any) => (
            <List.Item>
              <List.Item.Meta
                avatar={<UserOutlined style={{ color: '#1677ff' }} />}
                title={<Text style={{ fontSize: '13px' }}>{item.character}</Text>}
                description={<Text style={{ fontSize: '12px' }}>{item.state}</Text>}
              />
            </List.Item>
          )}
        />
      )
    });
  }

  if (pendingThreads.length > 0) {
    tabItems.push({
      key: 'pending',
      label: `待收线 (${pendingThreads.length})`,
      children: (
        <List
          size="small"
          dataSource={pendingThreads}
          renderItem={(item: any) => (
            <List.Item>
              <Badge status="warning" />
              <Text style={{ fontSize: '12px', marginLeft: '8px' }}>{item.description}</Text>
            </List.Item>
          )}
        />
      )
    });
  }

  if (foreshadowing.length > 0) {
    tabItems.push({
      key: 'foreshadowing',
      label: `伏笔 (${foreshadowing.length})`,
      children: (
        <List
          size="small"
          dataSource={foreshadowing}
          renderItem={(item: any) => (
            <List.Item>
              <List.Item.Meta
                title={<Text style={{ fontSize: '13px' }}>{item.title}</Text>}
                description={<Text style={{ fontSize: '12px' }}>{item.description}</Text>}
              />
            </List.Item>
          )}
        />
      )
    });
  }

  return (
    <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
      <Tabs defaultActiveKey="all" size="small" items={tabItems} />
    </div>
  );
};

const EmptyMemoryState = () => (
  <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
    <BulbOutlined style={{ fontSize: '32px', marginBottom: '8px' }} />
    <p>随着剧情发展，Agent 会自动记录关键信息</p>
  </div>
);

// 辅助函数：获取记忆项颜色
function getMemoryColor(type: string): string {
  switch (type) {
    case 'timeline': return 'blue';
    case 'character_state': return 'green';
    case 'pending_thread': return 'orange';
    case 'foreshadowing': return 'purple';
    default: return 'gray';
  }
}

// 辅助函数：获取记忆项图标
function getMemoryIcon(type: string): React.ReactNode {
  switch (type) {
    case 'timeline': return <ClockCircleOutlined />;
    case 'character_state': return <UserOutlined />;
    case 'pending_thread': return <AlertOutlined />;
    case 'foreshadowing': return <BulbOutlined />;
    default: return <CheckCircleOutlined />;
  }
}
