import { useEffect, useState, useRef, useCallback } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Layout, Button, Space, message, Spin, Typography, Tag } from 'antd'
import { ArrowLeftOutlined, UnorderedListOutlined } from '@ant-design/icons'

import { projectService } from '@/services/projectService'
import { ContextPanel } from '@/components/Workspace/ContextPanel'
import { SmartCanvas } from '@/components/Workspace/SmartCanvas'
import { DirectorInbox } from '@/components/Workspace/DirectorInbox'
import { EpisodeSidebar } from '@/components/Workspace/EpisodeSidebar'
import { Episode } from '@/services/projectService'

const { Header, Content, Sider } = Layout;
const { Text } = Typography;

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

  // 调试：确认组件已加载
  console.log('=== ProjectWorkspace component loaded ===')
  console.log('projectId:', projectId)

  const [project, setProject] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [streaming, setStreaming] = useState(false)
  const [canvasContent, setCanvasContent] = useState<string>('')
  const [agentStatus, setAgentStatus] = useState<'idle' | 'planning' | 'writing' | 'reviewing'>('idle')
  const [agentPlan, setAgentPlan] = useState<string[]>([])
  const [inboxItems, setInboxItems] = useState<any[]>([])
  const [chatHistory, setChatHistory] = useState<{role: 'user' | 'agent', content: string}[]>([])
  const [annotations, setAnnotations] = useState<any[]>([])
  const [activeStates, setActiveStates] = useState<any[]>([
    { type: 'time', value: '初始状态' },
    { type: 'location', value: '未知地点' }
  ])

  // 记忆库状态
  const [memoryItems, setMemoryItems] = useState<any[]>([])

  // 剧集相关状态
  const [currentEpisode, setCurrentEpisode] = useState<Episode | null>(null)
  const [showEpisodeSidebar, setShowEpisodeSidebar] = useState(true)

  const [wsConnected, setWsConnected] = useState(false);

  // WebSocket refs
  const wsRef = useRef<WebSocket | null>(null);
  const reconnectTimeoutRef = useRef<number | null>(null);

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

  useEffect(() => {
    loadProject()
    
    return () => {
        if (reconnectTimeoutRef.current) {
            clearTimeout(reconnectTimeoutRef.current);
        }
        if (wsRef.current) {
            wsRef.current.close();
        }
    }
  }, [projectId])

  // WebSocket Connection Logic
  const connectWebSocket = useCallback(() => {
    if (!projectId) return;

    // Close existing connection if any
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      console.log('Closing existing WebSocket connection');
      wsRef.current.close();
    }

    // Use relative URL which will be proxied by Vite
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host; // e.g. localhost:5173
    const wsUrl = `${protocol}//${host}/ws/projects/${projectId}/execute`;

    console.log('Connecting to WebSocket:', wsUrl);
    const ws = new WebSocket(wsUrl);

    ws.onopen = () => {
      console.log('WebSocket Connected');
      setWsConnected(true);
      message.success('已连接到 Agent Runtime');
    };

    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);
        handleWebSocketMessage(msg);
      } catch (e) {
        console.error('Failed to parse WS message:', e);
      }
    };

    ws.onclose = () => {
      console.log('WebSocket Disconnected');
      setWsConnected(false);
      // Clear ref to allow reconnection
      if (wsRef.current === ws) {
        wsRef.current = null;
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket Error:', error);
      // Don't close here, let onclose handle it
    };

    wsRef.current = ws;
  }, [projectId]); // Only depend on projectId

  useEffect(() => {
    if (projectId && !loading) {
        connectWebSocket();
    }
    // Cleanup on unmount or projectId change
    return () => {
        if (reconnectTimeoutRef.current) {
            clearTimeout(reconnectTimeoutRef.current);
        }
        if (wsRef.current) {
            wsRef.current.close();
            wsRef.current = null;
        }
    };
  }, [projectId, loading, connectWebSocket]);

  const handleInboxAction = (itemId: string, action: 'approve' | 'reject') => {
    // Optimistic update
    setInboxItems(prev => prev.filter(item => item.id !== itemId));
    
    // Send to backend
    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify({
            type: 'inbox_action',
            itemId,
            action
        }));
    }
    
    message.success(action === 'approve' ? '已批准' : '已拒绝');
  };

  const handleWebSocketMessage = (msg: any) => {
    console.log('Received:', msg);
    
    switch (msg.type) {
        case 'connected':
            break;
        case 'history':
            if (msg.messages) {
                setChatHistory(msg.messages);
            }
            break;
        case 'thinking':
            // Optional: show thinking indicator in chat
            break;
        case 'text':
            setChatHistory(prev => {
                const lastMsg = prev[prev.length - 1];
                // 如果上一条消息也是 agent 发送的，则认为是流式输出，追加内容
                if (lastMsg && lastMsg.role === 'agent') {
                    const newHistory = [...prev];
                    newHistory[newHistory.length - 1] = {
                        ...lastMsg,
                        content: lastMsg.content + msg.content
                    };
                    return newHistory;
                }
                // 否则添加新消息
                return [...prev, { role: 'agent', content: msg.content }];
            });
            break;
        case 'plan_update':
            if (msg.plan) {
                setAgentPlan(msg.plan);
            }
            if (msg.status) {
                setAgentStatus(msg.status);
            }
            break;
        case 'review_request':
            setInboxItems(prev => [...prev, {
                id: msg.id || Date.now().toString(),
                type: 'review',
                title: msg.title || '需要审核',
                description: msg.description,
                status: 'pending',
                timestamp: Date.now()
            }]);
            break;
        case 'memory_hit':
            // 添加到记忆库
            if (msg.data) {
                setMemoryItems(prev => [...prev, {
                    type: msg.data.memory_type || 'timeline',
                    title: msg.data.title || '记忆更新',
                    description: msg.data.description || JSON.stringify(msg.data.data),
                    timestamp: Date.now()
                }]);
            }
            break;
        case 'memory_update':
            // 从 update_memory 工具触发的记忆更新
            if (msg.data) {
                setMemoryItems(prev => [...prev, {
                    type: msg.data.type || msg.data.memory_type || 'timeline',
                    title: msg.data.title || '记忆更新',
                    description: msg.data.description || '',
                    timestamp: msg.data.timestamp || Date.now(),
                    character: msg.data.character,
                    state: msg.data.state
                }]);
            }
            break;
        case 'annotation_add':
            setAnnotations(prev => [...prev, msg.annotation]);
            break;
        case 'context_update':
            if (msg.states) {
                setActiveStates(msg.states);
            }
            break;
        case 'tool_call':
            const toolData = msg.data || {};
            const toolName = toolData.name || msg.name;
            
            if (toolName === 'update_canvas' || toolName === 'write_file') {
                setStreaming(true);
                setAgentStatus('writing');
            } else {
                setAgentStatus('planning');
            }
            break;
        case 'tool_result':
            setStreaming(false);
            break;
        case 'canvas_update':
            if (msg.content) {
                setCanvasContent(msg.content);
                // 自动保存到当前剧集
                if (currentEpisode && currentEpisode.id) {
                    // 这里可以调用 API 保存到后端
                    console.log('Auto-saving content to episode:', currentEpisode.id);
                }
            }
            break;
        case 'episode_saved':
            // Agent 保存剧集后的确认
            message.success(`剧集 ${msg.episode_number || ''} 已自动保存`);
            break;
        case 'done':
            setAgentStatus('idle');
            setStreaming(false);
            break;
        case 'error':
            message.error(msg.data?.message || 'Unknown error');
            setAgentStatus('idle');
            break;
    }
  };

  const handleDirectorMessage = (msg: string) => {
    console.log('=== handleDirectorMessage called ===', msg);

    // Optimistically update chat history
    setChatHistory(prev => [...prev, { role: 'user', content: msg }]);

    // Send message to backend via WebSocket
    console.log('wsRef.current:', wsRef.current);
    console.log('wsRef.current?.readyState:', wsRef.current?.readyState);
    console.log('WebSocket.OPEN:', WebSocket.OPEN);

    if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
        const messagePayload = JSON.stringify({
            type: 'chat_message',
            content: msg
        });
        console.log('Sending message:', messagePayload);

        wsRef.current.send(messagePayload);
        console.log('Message sent successfully');

        // Optimistic UI update could happen here
        if (msg.includes("开始")) {
            setAgentStatus('planning');
        }
    } else {
        console.error('WebSocket not ready:', {
            exists: !!wsRef.current,
            readyState: wsRef.current?.readyState,
            OPEN: WebSocket.OPEN
        });
        message.error('Agent 连接未就绪');
    }
  }

  // 画布内容变更处理
  const handleContentChange = (content: string) => {
    setCanvasContent(content);
  }

  // 画布内容保存处理
  const handleContentSave = async (content: string) => {
    if (!currentEpisode || !currentEpisode.id) {
      message.warning('请先选择要保存的剧集');
      return;
    }

    try {
      // 调用后端 API 保存剧集内容
      await projectService.updateEpisode(currentEpisode.id, {
        content: content,
        status: 'draft'
      });
      message.success('内容已保存');
    } catch (error) {
      message.error(`保存失败: ${(error as Error).message}`);
    }
  }

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center', marginTop: '100px' }}>
        <Spin size="large" tip="正在初始化数字化片场..." />
      </div>
    )
  }

  if (!project) {
    return (
      <div style={{ padding: '24px', textAlign: 'center', marginTop: '100px' }}>
        <Text type="danger">项目加载失败或不存在</Text>
        <br />
        <Button onClick={() => navigate('/projects')} style={{ marginTop: '16px' }}>
          返回项目列表
        </Button>
      </div>
    )
  }

  return (
    <Layout style={{ height: '100vh' }}>
      <Header style={{
        background: '#fff',
        borderBottom: '1px solid #f0f0f0',
        padding: '0 24px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      }}>
        <Space>
          <Button
            type="text"
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate('/projects')}
          />
          <Text strong style={{ fontSize: '16px' }}>{project?.name}</Text>
          <Text type="secondary" style={{ fontSize: '12px' }}>ID: {projectId}</Text>
          <Tag color={wsConnected ? 'success' : 'error'}>
            {wsConnected ? '已连接' : '未连接'}
          </Tag>
          <Button
            type="text"
            icon={<UnorderedListOutlined />}
            onClick={() => setShowEpisodeSidebar(!showEpisodeSidebar)}
            style={{ color: showEpisodeSidebar ? '#1677ff' : '#666' }}
          >
            剧集列表
          </Button>
        </Space>

        <Space>
          <Button>导出剧本</Button>
          <Button type="primary">发布</Button>
        </Space>
      </Header>

      <Layout>
        {/* 剧集管理侧边栏 */}
        {showEpisodeSidebar && (
          <Sider width={280} style={{ background: '#fafafa', borderRight: '1px solid #f0f0f0' }}>
            <EpisodeSidebar
              projectId={projectId!}
              onEpisodeSelect={(episode) => {
                setCurrentEpisode(episode)
                // 可以在这里更新画布内容显示剧集内容
                if (episode.content) {
                  setCanvasContent(episode.content)
                }
              }}
              currentEpisodeId={currentEpisode?.id}
            />
          </Sider>
        )}

        {/* 左侧：Context Panel */}
        <ContextPanel
          project={project}
          loading={loading}
          activeStates={activeStates}
          memoryItems={memoryItems}
        />

        {/* 中间：Smart Canvas */}
        <Content style={{ position: 'relative' }}>
          <SmartCanvas
            content={canvasContent}
            streaming={streaming}
            annotations={annotations}
            episodeTitle={currentEpisode?.title || '未命名草稿'}
            episodeNumber={currentEpisode?.number || 5}
            onStartGenerate={() => {
              handleDirectorMessage('开始生成大纲');
            }}
            onContentChange={handleContentChange}
            onContentSave={handleContentSave}
          />
        </Content>

        {/* 右侧：Director Inbox */}
        <DirectorInbox
            onSendMessage={handleDirectorMessage}
            onInboxAction={handleInboxAction}
            agentStatus={agentStatus}
            agentPlan={agentPlan}
            inboxItems={inboxItems}
            chatHistory={chatHistory}
        />
      </Layout>
    </Layout>
  )
}
