import React, { useState, useEffect, useRef } from 'react';
import { Input, List, Avatar, Button, Card, Tag, Badge, Tooltip, Divider, Space, Popconfirm, Modal, message } from 'antd';
import {
  SendOutlined,
  RobotOutlined,
  UserOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  StopOutlined,
  ReloadOutlined,
  ClearOutlined,
  DeleteOutlined,
  WarningOutlined
} from '@ant-design/icons';

const { TextArea } = Input;

export interface InboxItem {
  id: string;
  type: 'review' | 'decision' | 'notification' | 'review_card' | 'confirm_card';
  title: string;
  description: string;
  status: 'pending' | 'approved' | 'rejected' | 'ignored';
  timestamp: number;
  options?: Array<{ id: string; label: string; description?: string; implications?: string }>;
  reviewData?: any;
  confirmData?: {
    card_id: string;
    allow_custom_response: boolean;
    expires_at?: string;
  };
}

interface DirectorInboxProps {
  onSendMessage: (message: string) => void;
  onStopAgent?: () => void;
  onInboxAction?: (itemId: string, action: 'approve' | 'reject') => void;
  onConfirmCardAction?: (itemId: string, action: 'confirm' | 'reject', selectedOptionId?: string, customResponse?: string) => void;
  onNavigateToReview?: (episodeNum: number) => void;
  onResetConversation?: () => void;  // 新增：重建对话回调
  agentStatus: 'idle' | 'planning' | 'writing' | 'reviewing';
  agentPlan?: string[];
  inboxItems?: InboxItem[];
  chatHistory?: {role: 'user' | 'agent', content: string}[];
  width?: number;
  wsRef?: React.RefObject<WebSocket | null>;  // 新增：WebSocket引用
}

export const DirectorInbox: React.FC<DirectorInboxProps> = ({
  onSendMessage,
  onStopAgent,
  onInboxAction,
  onConfirmCardAction,
  onNavigateToReview,
  onResetConversation,  // 新增：重建对话回调
  agentStatus,
  agentPlan = [],
  inboxItems = [],
  chatHistory = [],
  width = 400,
  wsRef  // 新增：WebSocket引用
}) => {
  const [inputValue, setInputValue] = useState('');
  // Use local state for immediate feedback, but sync with props if provided
  const [localMessages, setLocalMessages] = useState<{role: 'user' | 'agent', content: string}[]>([]);
  const [showClearConfirm, setShowClearConfirm] = useState(false);

  // 新增：处理重建对话（保留上下文，清除显示）
  const handleResetConversation = () => {
    // 清空本地消息，保留欢迎语
    setLocalMessages([{ role: 'agent', content: '导演你好，我是你的 AI 助手。' }]);

    // 通过WebSocket发送重建对话请求
    if (wsRef && wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'reset_conversation'
      }));
    }

    // 调用父组件回调
    onResetConversation?.();

    message.success('对话已刷新，上下文已保留');
  };

  // 新增：完全清除对话（包括上下文）
  const handleClearConversation = () => {
    setShowClearConfirm(true);
  };

  const confirmClearConversation = () => {
    // 清空本地消息
    setLocalMessages([{ role: 'agent', content: '导演你好，我是你的 AI 助手。' }]);

    // 通过WebSocket发送清除对话请求（完全重置）
    if (wsRef && wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'clear_conversation'
      }));
    }

    // 调用父组件回调
    onResetConversation?.();

    setShowClearConfirm(false);
    message.success('对话已完全清除，上下文已重置');
  };

  // 检查对话长度，超过阈值提醒用户
  useEffect(() => {
    const MESSAGE_THRESHOLD = 30; // 超过30条消息提醒
    if (localMessages.length >= MESSAGE_THRESHOLD && localMessages.length === MESSAGE_THRESHOLD) {
      // 只有 Agent 才能发送提醒
      const hasReminder = localMessages.some(m =>
        m.role === 'agent' && m.content.includes('对话记录较长，建议您')
      );
      if (!hasReminder) {
        message.warning({
          content: '对话记录较长，建议您刷新或清除对话以获得更好性能',
          duration: 5,
          icon: <WarningOutlined style={{ color: '#faad14' }} />
        });
      }
    }
  }, [localMessages]);

  useEffect(() => {
    // 确保 chatHistory 是数组
    if (Array.isArray(chatHistory) && chatHistory.length > 0) {
        setLocalMessages(chatHistory);
    } else if (localMessages.length === 0) {
         setLocalMessages([{ role: 'agent', content: '导演你好，我是你的 AI 助手。' }]);
    }
  }, [chatHistory]);

  const messagesEndRef = useRef<HTMLDivElement>(null);

  const handleSend = () => {
    if (!inputValue.trim()) return;
    const newMsg = { role: 'user' as const, content: inputValue };
    setLocalMessages(prev => [...prev, newMsg]);
    onSendMessage(inputValue);
    setInputValue('');
  };

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [localMessages]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'planning': return 'blue';
      case 'writing': return 'green';
      case 'reviewing': return 'orange';
      default: return 'default';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'planning': return '规划中...';
      case 'writing': return '撰写中...';
      case 'reviewing': return '自查中...';
      default: return '待命';
    }
  };

  const handleInboxItemClick = (item: InboxItem) => {
    if (item.type === 'review_card' && item.reviewData) {
      if (onNavigateToReview) {
        onNavigateToReview(item.reviewData.episode_number);
      }
    }
  };

  return (
    <div
      style={{
        width: '100%',
        height: '100%',
        background: '#fafbfc',
        border: '1px solid #e0e4e7',
        borderLeft: 'none',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
        borderRadius: '0 8px 8px 0',
        boxShadow: 'inset 1px 0 0 #e5e7eb'
      }}
    >
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        overflow: 'hidden'
      }}>
        {/* Agent 状态与计划 */}
        <div style={{ padding: '16px', borderBottom: '2px solid #e0e4e7', background: 'linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)', flexShrink: 0, boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
            <Avatar icon={<RobotOutlined />} style={{ backgroundColor: '#1890ff', marginRight: '8px' }} />
            <div>
              <div style={{ fontWeight: 'bold' }}>AI Director Agent</div>
              <Tag color={getStatusColor(agentStatus)}>
                {agentStatus !== 'idle' && <LoadingOutlined style={{ marginRight: '4px' }} />}
                {getStatusText(agentStatus)}
              </Tag>
            </div>
          </div>
          
          {Array.isArray(agentPlan) && agentPlan.length > 0 && (
            <Card size="small" title="当前执行计划" style={{ marginTop: '8px' }}>
               <ul style={{ paddingLeft: '20px', margin: 0 }}>
                 {agentPlan.map((step, idx) => (
                   <li key={idx} style={{ color: idx === 0 ? '#1890ff' : '#666' }}>{step}</li>
                 ))}
               </ul>
            </Card>
          )}
        </div>

        {/* 导演信箱 (Inbox) */}
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          maxHeight: '40%',
          background: '#f5f6f8',
          borderBottom: '1px solid #e0e4e7',
          flexShrink: 0
        }}>
          <div style={{ padding: '8px 12px', background: '#f0f2f5', borderBottom: '1px solid #e8e8e8', flexShrink: 0 }}>
            <Divider orientation="left" style={{ margin: 0, fontSize: '12px', borderTopColor: '#d9d9d9' }}>待处理任务 (Inbox)</Divider>
          </div>
          <div style={{
            padding: '12px 16px',
            overflowY: 'auto',
            overflowX: 'hidden',
            flex: 1
          }}>
            {Array.isArray(inboxItems) && inboxItems.map(item => (
              <Card
                key={item.id}
                size="small"
                style={{
                  marginBottom: '8px',
                  borderLeft: item.type === 'review_card' ? '3px solid #1890ff' :
                               item.type === 'confirm_card' ? '3px solid #52c41a' : '3px solid #faad14',
                  cursor: item.type === 'review_card' ? 'pointer' : 'default',
                  borderRadius: '6px'
                }}
                onClick={() => item.type !== 'confirm_card' ? handleInboxItemClick(item) : undefined}
                hoverable={item.type === 'review_card'}
                actions={
                  item.type === 'review_card' ? [] :
                  item.type === 'confirm_card' ? [
                    <Tooltip key="reject" title="拒绝">
                      <Button
                        type="text"
                        size="small"
                        icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
                        onClick={() => onConfirmCardAction?.(item.id, 'reject')}
                      />
                    </Tooltip>
                  ] : [
                    <Tooltip key="approve" title="批准/确认">
                      <Button
                        type="text"
                        size="small"
                        icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                        onClick={() => onInboxAction?.(item.id, 'approve')}
                      />
                    </Tooltip>,
                    <Tooltip key="reject" title="拒绝/修改">
                      <Button
                        type="text"
                        size="small"
                        icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
                        onClick={() => onInboxAction?.(item.id, 'reject')}
                      />
                    </Tooltip>
                  ]
                }
              >
                <Card.Meta
                  avatar={
                    item.type === 'review_card' ? <CheckCircleOutlined style={{ color: '#1890ff', fontSize: '20px' }} /> :
                    item.type === 'confirm_card' ? <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '20px' }} /> :
                    <ExclamationCircleOutlined style={{ color: '#faad14', fontSize: '20px' }} />
                  }
                  title={<span style={{ fontSize: '14px', fontWeight: 600 }}>{item.title}</span>}
                  description={
                    <div>
                      <div style={{ fontSize: '12px', color: '#666', wordBreak: 'break-word' }}>{item.description}</div>
                      {item.type === 'confirm_card' && item.options && item.options.length > 0 && (
                        <div style={{ marginTop: '12px' }}>
                          <Space direction="vertical" size="small" style={{ width: '100%' }}>
                            {item.options.map((option) => (
                              <Button
                                key={option.id}
                                size="small"
                                type="primary"
                                ghost
                                block
                                style={{ textAlign: 'left', height: 'auto', padding: '4px 8px' }}
                                onClick={() => onConfirmCardAction?.(item.id, 'confirm', option.id)}
                              >
                                <div>
                                  <div style={{ fontWeight: 500 }}>{option.label}</div>
                                  {option.description && (
                                    <div style={{ fontSize: '11px', color: '#666', marginTop: '2px' }}>
                                      {option.description}
                                    </div>
                                  )}
                                </div>
                              </Button>
                            ))}
                          </Space>
                        </div>
                      )}
                    </div>
                  }
                />
              </Card>
            ))}
            {(!inboxItems || inboxItems.length === 0) && (
              <div style={{ textAlign: 'center', padding: '12px', color: '#999', fontSize: '12px' }}>暂无待处理任务</div>
            )}
          </div>
        </div>

        {/* 对话记录 */}
        <div style={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          background: '#f5f6f8',
          overflow: 'hidden'
        }}>
          <div style={{ 
            padding: '8px 12px', 
            background: '#f0f2f5', 
            borderBottom: '1px solid #e8e8e8',
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center',
            flexShrink: 0
          }}>
            <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
              <Divider orientation="left" style={{ margin: 0, fontSize: '12px', borderTopColor: '#d9d9d9' }}>对话记录</Divider>
            </div>
            <Tooltip title="重建对话（清除历史但保留上下文）">
              <Button
                type="text"
                size="small"
                icon={<ReloadOutlined style={{ fontSize: '12px' }} />}
                onClick={handleResetConversation}
                style={{ 
                  fontSize: '11px', 
                  display: 'flex', 
                  alignItems: 'center', 
                  color: '#1890ff',
                  padding: '0 8px',
                  height: '24px',
                  marginLeft: '8px'
                }}
              >
                重建
              </Button>
            </Tooltip>
          </div>

          <div style={{
            flex: 1,
            overflowY: 'auto',
            overflowX: 'hidden',
            padding: '16px',
            display: 'flex',
            flexDirection: 'column'
          }}>
            {Array.isArray(localMessages) && localMessages.map((msg, idx) => (
              <div key={idx} style={{ 
                display: 'flex', 
                justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
                marginBottom: '12px',
                width: '100%'
              }}>
                <div style={{ 
                  maxWidth: '90%', 
                  padding: '8px 12px', 
                  borderRadius: '12px',
                  background: msg.role === 'user' ? '#1890ff' : '#fff',
                  color: msg.role === 'user' ? '#fff' : '#333',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.05)',
                  wordBreak: 'break-word',
                  whiteSpace: 'pre-wrap',
                  fontSize: '13px',
                  lineHeight: '1.5'
                }}>
                  {msg.content}
                </div>
              </div>
            ))}
            <div ref={messagesEndRef} />
          </div>
        </div>

        {/* 输入框 */}
        <div style={{ padding: '16px', borderTop: '2px solid #e0e4e7', background: '#ffffff', flexShrink: 0, boxShadow: '0 -1px 3px rgba(0,0,0,0.04)' }}>
          <div style={{ display: 'flex' }}>
            <TextArea
              rows={2}
              value={inputValue}
              onChange={e => setInputValue(e.target.value)}
              onPressEnter={(e) => {
                if (!e.shiftKey) {
                  e.preventDefault();
                  if (agentStatus !== 'idle') {
                    onStopAgent?.();
                  } else {
                    handleSend();
                  }
                }
              }}
              placeholder={agentStatus !== 'idle' ? 'Agent 正在运行中...' : '给 Agent 下达指令...'}
              disabled={agentStatus !== 'idle'}
              style={{ resize: 'none', marginRight: '8px' }}
            />
            <Button
              type={agentStatus !== 'idle' ? 'default' : 'primary'}
              danger={agentStatus !== 'idle'}
              shape="circle"
              icon={agentStatus !== 'idle' ? <StopOutlined /> : <SendOutlined />}
              size="large"
              onClick={agentStatus !== 'idle' ? onStopAgent : handleSend}
            />
          </div>
        </div>

        {/* 清除对话确认弹窗 */}
        <Modal
          title={
            <Space>
              <WarningOutlined style={{ color: '#ff4d4f' }} />
              <span>确认清除对话</span>
            </Space>
          }
          open={showClearConfirm}
          onOk={confirmClearConversation}
          onCancel={() => setShowClearConfirm(false)}
          okText="确认清除"
          cancelText="取消"
          okButtonProps={{ danger: true }}
        >
          <div style={{ padding: '16px 0' }}>
            <p style={{ marginBottom: '12px', color: '#666' }}>
              您确定要<strong style={{ color: '#ff4d4f' }}>完全清除对话</strong>吗？
            </p>
            <ul style={{ paddingLeft: '20px', color: '#666' }}>
              <li>所有聊天记录将被删除</li>
              <li>Agent 的上下文将被完全重置</li>
              <li>当前工作状态将被清空</li>
            </ul>
            <p style={{ marginTop: '12px', color: '#999', fontSize: '13px' }}>
              如果您只是想刷新显示，请使用"刷新"功能代替。
            </p>
          </div>
        </Modal>
      </div>
    </div>
  );
};
