/**
 * @name 聚合聊天
 * 
 * 参考资料：
 * - /rules/development-standards.md
 * - /rules/axure-api-guide.md
 * - /assets/docs/设计指导（简约）.md
 * - /src/themes/antd-new/DESIGN-SPEC.md
 */

import './style.css';

import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useState } from 'react';
import {
  Layout,
  Card,
  List,
  Avatar,
  Typography,
  Tag,
  Space,
  Input,
  Button,
  Tabs,
  Badge,
  Divider,
  Select,
  Tooltip,
  Empty,
  DatePicker
} from 'antd';
import {
  SearchOutlined,
  NotificationOutlined,
  SettingOutlined,
  SendOutlined,
  UserAddOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  MoreOutlined,
  TagOutlined,
  ExclamationCircleFilled,
  UserOutlined,
  TeamOutlined,
  ShopOutlined,
  AppstoreOutlined,
  HistoryOutlined,
  FileTextOutlined,
  SmileOutlined,
  PictureOutlined,
  AppstoreAddOutlined,
  LinkOutlined,
  FolderOpenOutlined,
  DesktopOutlined,
  MonitorOutlined
} from '@ant-design/icons';
import type { AxureProps, AxureHandle, EventItem, Action, KeyDesc, ConfigItem, DataDesc } from '../../common/axure-types';
import { MENU_ITEMS, resolveMenuTarget } from '../../common/menu';
import SideMenu from '../../components/side-menu';

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

// --- Mock Data ---

const MANAGED_ACCOUNTS = [
  { id: 'acc-1', name: '上海总店托管', isOnline: true, hasUnread: true, hasException: false, avatar: 'SH', staffName: '张三' },
  { id: 'acc-2', name: '北京分部客服', isOnline: true, hasUnread: false, hasException: false, avatar: 'BJ', staffName: '李四' },
  { id: 'acc-3', name: '深圳售后专线', isOnline: false, hasUnread: true, hasException: true, avatar: 'SZ', staffName: '王五' },
  { id: 'acc-4', name: '广州运营号01', isOnline: true, hasUnread: false, hasException: false, avatar: 'GZ', staffName: '赵六' },
  { id: 'acc-5', name: '成都活动号', isOnline: true, hasUnread: false, hasException: false, avatar: 'CD', staffName: '孙七' },
];

const CONTACTS = [
  { id: 'u-1', name: '王总', avatar: '', tags: ['VIP'], accountId: 'acc-1' },
  { id: 'u-2', name: '李经理', avatar: '', tags: ['潜在'], accountId: 'acc-1' },
  { id: 'u-3', name: '陈女士', avatar: '', tags: ['意向'], accountId: 'acc-2' },
  { id: 'u-4', name: '赵先生', avatar: '', tags: ['老客'], accountId: 'acc-3' },
  { id: 'u-5', name: '孙小姐', avatar: '', tags: [], accountId: 'acc-1' },
];

const DEFAULT_CONVERSATIONS = [
  {
    id: 'conv-1',
    name: '林晓敏',
    avatar: '',
    last_message: '已发送资费说明书，等待确认。',
    unread_count: 2,
    status: 'pending',
    channel: '企业微信',
    accountId: 'acc-1',
    time: '09:15'
  },
  {
    id: 'conv-2',
    name: '许晨',
    avatar: '',
    last_message: '客户需要周五前完成迁移。',
    unread_count: 0,
    status: 'in_progress',
    channel: '企微群',
    accountId: 'acc-2',
    time: '10:25'
  },
  {
    id: 'conv-3',
    name: '张浩',
    avatar: '',
    last_message: '已安排下周回访。',
    unread_count: 0,
    status: 'done',
    channel: '公众号',
    accountId: 'acc-3',
    time: '昨天'
  },
  {
    id: 'conv-4',
    name: '王小丽',
    avatar: '',
    last_message: '谢谢您的解答',
    unread_count: 1,
    status: 'pending',
    channel: '企业微信',
    accountId: 'acc-1',
    time: '09:00'
  }
];

const DEFAULT_MESSAGES: Record<string, Array<any>> = {
  'conv-1': [
    { id: 'm1', direction: 'in', type: 'text', content: '你好，想了解最新资费。', time: '09:12' },
    { id: 'm2', direction: 'out', type: 'text', content: '已整理资费说明，稍后发您。', time: '09:14' },
    { id: 'm3', direction: 'out', type: 'file', content: '资费说明书_2026版.pdf', time: '09:15' },
    { id: 'm3-1', direction: 'in', type: 'image', content: 'https://picsum.photos/200/150', time: '09:16' },
    { id: 'm3-2', direction: 'out', type: 'miniprogram', content: { title: '拼团优惠活动', desc: '限时3人成团，点击查看详情', icon: '🎁' }, time: '09:17' },
    { id: 'm3-3', direction: 'in', type: 'h5', content: { title: '产品介绍页', desc: '浏览我们的核心产品系列', url: 'https://example.com' }, time: '09:18' }
  ],
  'conv-2': [
    { id: 'm4', direction: 'in', type: 'text', content: '迁移窗口能否提前？', time: '10:22' },
    { id: 'm5', direction: 'out', type: 'text', content: '可以安排在周四晚间，已同步工程。', time: '10:25' }
  ],
  'conv-3': [
    { id: 'm6', direction: 'in', type: 'text', content: '谢谢提醒，我们已准备好资料。', time: '11:10' },
    { id: 'm7', direction: 'out', type: 'link', content: 'https://example.com/flow', time: '11:12' }
  ]
};

// --- Axure Definitions ---

const EVENT_LIST: EventItem[] = [
  { name: 'on_conversation_select', desc: '选择会话时触发' },
  { name: 'on_account_select', desc: '选择托管账号时触发' }
];

const ACTION_LIST: Action[] = [
  { name: 'set_active_conversation', desc: '切换当前会话', params: 'string' }
];

const Component = forwardRef<AxureHandle, AxureProps>(function AggregateChat(innerProps, ref) {
  const dataSource = innerProps?.data || {};
  const configSource = innerProps?.config || {};
  const onEventHandler = innerProps?.onEvent || (() => {});

  // State
  const [activeAccountId, setActiveAccountId] = useState<string>('all');
  const [activeConversationId, setActiveConversationId] = useState<string>('conv-1');
  const [navTab, setNavTab] = useState<'messages' | 'contacts'>('messages');
  const [rightTab, setRightTab] = useState('materials');
  const [showRightPanel, setShowRightPanel] = useState(false);
  const [contactSearch, setContactSearch] = useState('');
  
  const [draftText, setDraftText] = useState('');
  const [messagesByConversation, setMessagesByConversation] = useState(DEFAULT_MESSAGES);

  const fileInputRef = React.useRef<HTMLInputElement>(null);

  // Derived Data
  const conversationList = useMemo(() => {
    return (dataSource.conversations || DEFAULT_CONVERSATIONS).filter((c: any) => {
      // Account Filter
      if (activeAccountId !== 'all' && c.accountId !== activeAccountId) return false;
      return true;
    });
  }, [dataSource.conversations, activeAccountId]);

  const contactList = useMemo(() => {
    return CONTACTS.filter(c => {
      if (activeAccountId !== 'all' && c.accountId !== activeAccountId) return false;
      if (contactSearch && !c.name.includes(contactSearch)) return false;
      return true;
    });
  }, [activeAccountId, contactSearch]);

  const activeMessages = messagesByConversation[activeConversationId] || [];

  // Handlers
  const handleAccountSelect = (id: string) => {
    setActiveAccountId(id);
    onEventHandler('on_account_select', id);
  };

  const handleConversationSelect = (id: string) => {
    setActiveConversationId(id);
    onEventHandler('on_conversation_select', id);
  };

  const handleSend = () => {
    if (!draftText.trim()) return;
    setMessagesByConversation(prev => {
      const next = { ...prev };
      const list = next[activeConversationId] ? [...next[activeConversationId]] : [];
      list.push({
        id: `m-${Date.now()}`,
        direction: 'out',
        type: 'text',
        content: draftText,
        time: '刚刚'
      });
      next[activeConversationId] = list;
      return next;
    });
    setDraftText('');
  };

  const handleHistoryToggle = () => {
    if (showRightPanel && rightTab === 'history') {
      setShowRightPanel(false);
    } else {
      setShowRightPanel(true);
      setRightTab('history');
    }
  };

  const handleToolsToggle = () => {
    if (showRightPanel && rightTab !== 'history') {
      setShowRightPanel(false);
    } else {
      setShowRightPanel(true);
      if (rightTab === 'history') setRightTab('materials');
    }
  };

  const handleFileUpload = () => {
    fileInputRef.current?.click();
  };

  const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setMessagesByConversation(prev => {
        const next = { ...prev };
        const list = next[activeConversationId] ? [...next[activeConversationId]] : [];
        list.push({
          id: `m-${Date.now()}`,
          direction: 'out',
          type: 'file',
          content: file.name,
          time: '刚刚'
        });
        next[activeConversationId] = list;
        return next;
      });
    }
    // Reset input
    if (e.target) e.target.value = '';
  };

  const renderMessageContent = (msg: any) => {
    switch (msg.type) {
      case 'file':
        return (
          <div className="aggregate-chat-msg-file">
            <FileTextOutlined style={{ fontSize: 24, color: '#1890ff' }} />
            <div style={{ marginLeft: 8 }}>
              <div style={{ fontWeight: 500 }}>{typeof msg.content === 'string' ? msg.content : '未知文件'}</div>
              <Text type="secondary" style={{ fontSize: 10 }}>245 KB</Text>
            </div>
          </div>
        );
      case 'image':
        return (
          <div className="aggregate-chat-msg-image">
             <img src={msg.content} alt="图片" style={{ maxWidth: '100%', borderRadius: 8 }} />
          </div>
        );
      case 'miniprogram':
        return (
          <div className="aggregate-chat-msg-card">
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <AppstoreAddOutlined style={{ color: '#faad14', marginRight: 4 }} />
              <Text type="secondary" style={{ fontSize: 10 }}>小程序</Text>
            </div>
            <div style={{ fontWeight: 500, marginBottom: 4 }}>{msg.content.title}</div>
            <Text type="secondary" style={{ fontSize: 12 }}>{msg.content.desc}</Text>
            <Divider style={{ margin: '8px 0' }} />
            <div style={{ display: 'flex', alignItems: 'center', fontSize: 12, color: '#1890ff' }}>
              <span style={{ marginRight: 4 }}>{msg.content.icon}</span> 小程序
            </div>
          </div>
        );
      case 'h5':
        return (
           <div className="aggregate-chat-msg-card">
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <LinkOutlined style={{ color: '#1890ff', marginRight: 4 }} />
              <Text type="secondary" style={{ fontSize: 10 }}>网页链接</Text>
            </div>
            <div style={{ fontWeight: 500, marginBottom: 4 }}>{msg.content.title}</div>
            <Text type="secondary" style={{ fontSize: 12 }}>{msg.content.desc}</Text>
          </div>
        );
      case 'text':
      default:
        return msg.content;
    }
  };

  const handleMenuSelect = useCallback(function (key: string) {
    const target = resolveMenuTarget(key);
    if (target) {
      window.location.href = target;
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getVar: (name) => {
      if (name === 'active_conversation_id') return activeConversationId;
      return undefined;
    },
    fireAction: (name, params) => {
      if (name === 'set_active_conversation' && params) setActiveConversationId(params);
    },
    eventList: EVENT_LIST,
    actionList: ACTION_LIST,
    varList: [],
    configList: [],
    dataList: []
  }));

  const getAccountName = (accId: string) => {
    return MANAGED_ACCOUNTS.find(a => a.id === accId)?.name || '未知账号';
  };

  const getAccountStaff = (accId: string) => {
    return MANAGED_ACCOUNTS.find(a => a.id === accId)?.staffName || '未分配';
  };

  // Render Tool Content (Iframe Placeholder)
  const renderToolContent = () => {
    if (rightTab === 'history') {
      const historyMessages = activeMessages; // Reuse active messages for demo
      return (
         <div className="aggregate-chat-tool-history">
           <div style={{ padding: 12, borderBottom: '1px solid #f0f0f0' }}>
             <Input placeholder="搜索历史记录" prefix={<SearchOutlined />} style={{ marginBottom: 8 }} />
             <DatePicker.RangePicker 
               style={{ width: '100%' }} 
               size="small"
               placeholder={['开始日期', '结束日期']}
             />
           </div>
           <div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
             {historyMessages.length === 0 ? <Empty description="暂无历史记录" /> : (
               <div className="aggregate-chat-history-list">
                 {historyMessages.map((msg: any) => (
                   <div key={msg.id} style={{ marginBottom: 16 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                        <Text strong style={{ fontSize: 12 }}>{msg.direction === 'out' ? '我' : '客户'}</Text>
                        <Text type="secondary" style={{ fontSize: 10 }}>{msg.time}</Text>
                      </div>
                      <div style={{ color: '#666', fontSize: 13 }}>
                        {['text'].includes(msg.type) ? msg.content : `[${msg.type}] 消息`}
                      </div>
                   </div>
                 ))}
               </div>
             )}
           </div>
         </div>
      );
    }
    
    // Mock Iframe URLs
    const toolUrls: Record<string, string> = {
      materials: 'https://example.com/materials',
      customer: 'https://example.com/customer-detail',
      ticket: 'https://example.com/tickets',
      feedback: 'https://example.com/feedback',
      scripts: 'https://example.com/scripts',
    };

    return (
      <div className="aggregate-chat-iframe-container">
        <div className="aggregate-chat-iframe-mask">
          <Text type="secondary">此处嵌入第三方页面: {toolUrls[rightTab]}</Text>
          <Button type="link">在新窗口打开</Button>
        </div>
      </div>
    );
  };

  return (
    <Layout className="aggregate-chat-page" hasSider>
      <SideMenu
        title="企微运营"
        width={280}
        defaultSelectedKey="im"
        items={MENU_ITEMS}
        onMenuSelect={handleMenuSelect}
      />
      <Layout style={{ overflow: 'hidden' }}>
        <Header className="aggregate-chat-header">
          <div className="aggregate-chat-header-left">
            <Title level={4}>聚合聊天</Title>
            <Text type="secondary">多账号聚合管理工作台</Text>
          </div>
          <Space size={20}>
            <Badge count={0} showZero>
              <NotificationOutlined />
            </Badge>
            <Button type="text" icon={<SettingOutlined />} />
            <Space size={8}>
              <Avatar size={32} icon={<UserOutlined />} />
              <Text>下午好, 代兆云</Text>
            </Space>
          </Space>
        </Header>

        <Content className="aggregate-chat-content">
          <div className="aggregate-chat-columns-v2">
            
            {/* Col 1: Managed Accounts (Narrow Sidebar) */}
            <div className="aggregate-chat-col-narrow">
              <div 
                className={`aggregate-chat-account-icon ${activeAccountId === 'all' ? 'active' : ''}`}
                onClick={() => handleAccountSelect('all')}
              >
                <Tooltip title="全部账号" placement="right">
                  <Avatar shape="square" icon={<AppstoreOutlined />} style={{ backgroundColor: activeAccountId === 'all' ? '#1890ff' : '#d9d9d9' }} />
                </Tooltip>
              </div>
              <Divider style={{ margin: '12px 0' }} />
              {MANAGED_ACCOUNTS.map(acc => (
                <div 
                  key={acc.id}
                  className={`aggregate-chat-account-icon ${activeAccountId === acc.id ? 'active' : ''}`}
                  onClick={() => handleAccountSelect(acc.id)}
                >
                  <Tooltip title={acc.name} placement="right">
                    <Badge dot={acc.hasUnread || acc.hasException} color={acc.hasException ? 'gold' : 'red'}>
                       <Avatar shape="square" style={{ backgroundColor: activeAccountId === acc.id ? '#1890ff' : '#87d068' }}>{acc.avatar}</Avatar>
                    </Badge>
                  </Tooltip>
                  <div className={`aggregate-chat-status-dot ${acc.isOnline ? 'online' : 'offline'}`} />
                </div>
              ))}
            </div>

            {/* Col 2: Navigation List (Tabbed) */}
            <div className="aggregate-chat-col-card">
              <div className="aggregate-chat-col-header" style={{ padding: '0 8px' }}>
                <Tabs 
                  activeKey={navTab} 
                  onChange={(k) => setNavTab(k as any)}
                  items={[
                    { key: 'messages', label: '消息列表' },
                    { key: 'contacts', label: '通讯录' }
                  ]}
                  style={{ width: '100%', marginBottom: -16 }}
                />
              </div>
              
              <div className="aggregate-chat-col-body">
                {navTab === 'messages' ? (
                  <>
                    <div className="aggregate-chat-search-bar">
                      <Input placeholder="搜索消息" prefix={<SearchOutlined />} />
                    </div>
                    <List
                      dataSource={conversationList}
                      renderItem={(item: any) => (
                        <div 
                          className={`aggregate-chat-msg-item ${activeConversationId === item.id ? 'active' : ''}`}
                          onClick={() => handleConversationSelect(item.id)}
                        >
                          <Space align="start" style={{ width: '100%' }}>
                            <Badge count={item.unread_count} size="small">
                              <Avatar shape="square" src={item.avatar || undefined}>{item.name?.[0]}</Avatar>
                            </Badge>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                <Text strong>{item.name}</Text>
                                <Text type="secondary" style={{ fontSize: 11 }}>{item.time}</Text>
                              </div>
                              <Text type="secondary" ellipsis style={{ fontSize: 12, display: 'block' }}>
                                {item.last_message}
                              </Text>
                              <Tag style={{ marginTop: 4, fontSize: 10, lineHeight: '18px' }} bordered={false}>
                                {getAccountName(item.accountId)}
                              </Tag>
                            </div>
                          </Space>
                        </div>
                      )}
                    />
                  </>
                ) : (
                  <>
                     <div className="aggregate-chat-search-bar">
                      <Input 
                        placeholder="搜索联系人" 
                        prefix={<SearchOutlined />} 
                        value={contactSearch}
                        onChange={e => setContactSearch(e.target.value)}
                      />
                    </div>
                    {contactList.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无联系人" /> : (
                      <List
                        dataSource={contactList}
                        renderItem={(item) => (
                          <div className="aggregate-chat-contact-item">
                            <Avatar size="small" icon={<UserOutlined />} />
                            <div style={{ flex: 1 }}>
                              <Text>{item.name}</Text>
                              <div style={{ marginTop: 2 }}>
                                {item.tags.map(t => <Tag key={t} style={{ fontSize: 10 }}>{t}</Tag>)}
                              </div>
                            </div>
                          </div>
                        )}
                      />
                    )}
                  </>
                )}
              </div>
            </div>

            {/* Col 3: Chat Area (Main) */}
            <div className="aggregate-chat-col-card" style={{ flex: 1, borderRight: 'none' }}>
              <div className="aggregate-chat-col-header">
                <Space>
                  <Avatar style={{ backgroundColor: '#1890ff' }}>{DEFAULT_CONVERSATIONS.find(c => c.id === activeConversationId)?.name?.[0]}</Avatar>
                  <Space direction="vertical" size={0}>
                    <Space size={8} align="center">
                       <Text type="secondary" style={{ fontSize: 10 }}>
                         所属员工: {getAccountStaff(DEFAULT_CONVERSATIONS.find(c => c.id === activeConversationId)?.accountId || '')}
                       </Text>
                    </Space>
                    <Text strong>{DEFAULT_CONVERSATIONS.find(c => c.id === activeConversationId)?.name}</Text>
                    <Text type="secondary" style={{ fontSize: 10 }}>未备注手机号</Text>
                  </Space>
                </Space>
                <Space size={16}>
                  <Tooltip title="查看电脑状态">
                     <MonitorOutlined style={{ fontSize: 16, color: '#1890ff', cursor: 'pointer' }} />
                  </Tooltip>
                  <MoreOutlined style={{ fontSize: 16, cursor: 'pointer' }} />
                </Space>
              </div>
              <div className="aggregate-chat-chat-body">
                <div className="aggregate-chat-messages">
                  {activeMessages.map((msg: any) => (
                    <div key={msg.id} className={`aggregate-chat-message ${msg.direction}`}>
                      <div className="aggregate-chat-bubble">
                        {renderMessageContent(msg)}
                      </div>
                      <Text type="secondary" style={{ fontSize: 10 }}>{msg.time}</Text>
                    </div>
                  ))}
                </div>
                <div className="aggregate-chat-input-area">
                  <div className="aggregate-chat-toolbar">
                     <Space size={16}>
                        <SmileOutlined />
                        <Tooltip title="发送图片">
                          <PictureOutlined style={{ cursor: 'pointer' }} />
                        </Tooltip>
                        <Tooltip title="发送文件">
                          <FolderOpenOutlined onClick={handleFileUpload} style={{ cursor: 'pointer' }} />
                        </Tooltip>
                        <div style={{ width: 1, height: 16, background: '#f0f0f0' }} />
                        <Tooltip title="常用工具">
                          <AppstoreOutlined 
                            style={{ color: (showRightPanel && rightTab !== 'history') ? '#1890ff' : undefined, cursor: 'pointer' }} 
                            onClick={handleToolsToggle}
                          />
                        </Tooltip>
                        <Tooltip title="聊天记录">
                          <HistoryOutlined 
                            style={{ color: (showRightPanel && rightTab === 'history') ? '#1890ff' : undefined, cursor: 'pointer' }} 
                            onClick={handleHistoryToggle}
                          />
                        </Tooltip>
                     </Space>
                     <input 
                       type="file"  
                       ref={fileInputRef} 
                       style={{ display: 'none' }} 
                       onChange={onFileChange} 
                     />
                  </div>
                  <Input.TextArea 
                    autoSize={{ minRows: 3, maxRows: 6 }} 
                    placeholder="输入消息..." 
                    value={draftText}
                    onChange={e => setDraftText(e.target.value)}
                    bordered={false}
                    style={{ marginBottom: 8, resize: 'none' }}
                  />
                  <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button type="primary" onClick={handleSend}>发送消息</Button>
                  </div>
                </div>
              </div>
            </div>

            {/* Col 4: Right Sidebar (Tools) */}
            {showRightPanel && (
              <div className="aggregate-chat-col-card" style={{ width: 350, flexShrink: 0 }}>
                <div className="aggregate-chat-col-header" style={{ padding: '0 8px' }}>
                  <Tabs 
                    activeKey={rightTab} 
                    onChange={setRightTab}
                    items={[
                      { key: 'materials', label: '素材库' },
                      { key: 'customer', label: '客户详情' },
                      { key: 'ticket', label: '网格工单' },
                      { key: 'history', label: '聊天记录' }, 
                    ]}
                    style={{ width: '100%', marginBottom: -16 }}
                    tabBarStyle={{ fontSize: 12 }}
                  />
                </div>
                <div className="aggregate-chat-col-body">
                  {renderToolContent()}
                </div>
              </div>
            )}

          </div>
        </Content>
      </Layout>
    </Layout>
  );
});

export default Component;
