import React, { useState, useEffect, useRef } from 'react';
import { Layout, Input, List, Avatar, Button, Card, Tag, Badge, Tooltip, Divider } from 'antd';
import { 
  SendOutlined, 
  RobotOutlined, 
  UserOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons';

const { Sider } = Layout;
const { TextArea } = Input;

export interface InboxItem {
  id: string;
  type: 'review' | 'decision' | 'notification';
  title: string;
  description: string;
  status: 'pending' | 'approved' | 'rejected' | 'ignored';
  timestamp: number;
  options?: string[];
}

interface DirectorInboxProps {
  onSendMessage: (message: string) => void;
  onInboxAction?: (itemId: string, action: 'approve' | 'reject') => void;
  agentStatus: 'idle' | 'planning' | 'writing' | 'reviewing';
  agentPlan?: string[];
  inboxItems?: InboxItem[];
  chatHistory?: {role: 'user' | 'agent', content: string}[];
}

export const DirectorInbox: React.FC<DirectorInboxProps> = ({ 
  onSendMessage, 
  onInboxAction,
  agentStatus,
  agentPlan = [],
  inboxItems = [],
  chatHistory = []
}) => {
  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}[]>([]);

  useEffect(() => {
    if (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 '待命';
    }
  };

  return (
    <Sider 
      width={400} 
      theme="light" 
      style={{ 
        borderLeft: '1px solid #f0f0f0', 
        height: '100%', 
        display: 'flex', 
        flexDirection: 'column',
        background: '#fff'
      }}
    >
      {/* Agent 状态与计划 */}
      <div style={{ padding: '16px', borderBottom: '1px solid #f0f0f0', background: '#fafafa' }}>
        <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>
        
        {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={{ flex: 1, overflowY: 'auto', padding: '16px', background: '#f0f2f5' }}>
        <Divider orientation="left" style={{ margin: '0 0 16px 0', fontSize: '12px' }}>待处理任务 (Inbox)</Divider>
        
        {inboxItems.map(item => (
          <Card 
            key={item.id} 
            size="small" 
            style={{ marginBottom: '8px', borderLeft: '3px solid #faad14' }}
            actions={[
              <Tooltip title="批准/确认"><Button type="text" size="small" icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />} onClick={() => onInboxAction?.(item.id, 'approve')} /></Tooltip>,
              <Tooltip title="拒绝/修改"><Button type="text" size="small" icon={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />} onClick={() => onInboxAction?.(item.id, 'reject')} /></Tooltip>
            ]}
          >
            <Card.Meta
              avatar={<ExclamationCircleOutlined style={{ color: '#faad14', fontSize: '20px' }} />}
              title={<span style={{ fontSize: '14px' }}>{item.title}</span>}
              description={<span style={{ fontSize: '12px' }}>{item.description}</span>}
            />
          </Card>
        ))}

        <Divider orientation="left" style={{ margin: '16px 0', fontSize: '12px' }}>对话记录</Divider>
        
        {localMessages.map((msg, idx) => (
          <div key={idx} style={{ 
            display: 'flex', 
            justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
            marginBottom: '12px'
          }}>
            <div style={{ 
              maxWidth: '80%', 
              padding: '8px 12px', 
              borderRadius: '8px',
              background: msg.role === 'user' ? '#1890ff' : '#fff',
              color: msg.role === 'user' ? '#fff' : '#333',
              boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
            }}>
              {msg.content}
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>

      {/* 输入框 */}
      <div style={{ padding: '16px', borderTop: '1px solid #f0f0f0' }}>
        <div style={{ display: 'flex' }}>
          <TextArea 
            rows={2} 
            value={inputValue}
            onChange={e => setInputValue(e.target.value)}
            onPressEnter={(e) => {
              if (!e.shiftKey) {
                e.preventDefault();
                handleSend();
              }
            }}
            placeholder="给 Agent 下达指令..." 
            style={{ resize: 'none', marginRight: '8px' }}
          />
          <Button type="primary" shape="circle" icon={<SendOutlined />} size="large" onClick={handleSend} />
        </div>
      </div>
    </Sider>
  );
};
