const { useState, useEffect, useCallback, useRef } = React;

function IMPage({ activeTab = 'chats', setActiveTab, showNew = false, onCloseNew }) {
  const { navigate, showToast, pageParams, goBack, requireLogin } = useApp();
  const [conversations, setConversations] = useState([]);
  const [groups, setGroups] = useState([]);
  const [friends, setFriends] = useState([]);
  const [currentUser, setCurrentUser] = useState(null);
  const [currentConv, setCurrentConv] = useState(null);
  const [messages, setMessages] = useState([]);
  const [messageInput, setMessageInput] = useState('');
  const [loading, setLoading] = useState(true);
  const msgEndRef = useRef(null);

  // Load user
  useEffect(() => {
    API.get('/user/current').then(res => {
      if (res.success) setCurrentUser(res.data);
    });
  }, []);

  // Load conversations (merge single + group)
  const loadConversations = useCallback(() => {
    API.get('/im/conversations').then(res => {
      if (res.success) setConversations(res.data || []);
    });
  }, []);

  useEffect(() => {
    if (activeTab === 'chats') loadConversations();
  }, [activeTab, loadConversations]);

  // Load groups
  useEffect(() => {
    if (activeTab === 'groups') {
      API.get('/im/groups').then(res => {
        if (res.success) setGroups(res.data || []);
      });
    }
  }, [activeTab]);

  // Load friends
  useEffect(() => {
    if (activeTab === 'contacts') {
      API.get('/im/friends').then(res => {
        if (res.success) setFriends(res.data || []);
      });
    }
  }, [activeTab]);

  const loadMessages = useCallback(async (convId) => {
    const res = await API.get(`/im/conversations/${convId}/messages`);
    if (res.success) {
      setMessages(res.data || []);
      setTimeout(() => {
        msgEndRef.current?.scrollIntoView({ behavior: 'smooth' });
      }, 100);
    }
  }, []);

  const openConversation = (conv) => {
    setCurrentConv(conv);
    loadMessages(conv.id);
  };

  const closeChat = () => {
    setCurrentConv(null);
    setMessages([]);
    setMessageInput('');
  };

  const openFriendChat = async (friend) => {
    const res = await API.post('/im/conversations', { friend_id: friend.friend_id });
    if (res.success) {
      const conv = res.data;
      if (!conv.name) conv.name = friend.nickname;
      openConversation(conv);
    }
  };

  // Open chat with a user by user_id
  const openChatWithUser = useCallback(async (userId, userName) => {
    if (!userId) return;
    try {
      const res = await API.post('/im/conversations', { friend_id: userId });
      if (res.success) {
        const conv = res.data;
        if (!conv.name && userName) conv.name = userName;
        const listRes = await API.get('/im/conversations');
        if (listRes.success) setConversations(listRes.data || []);
        openConversation(conv);
      } else {
        showToast(res.message || '打开聊天失败');
      }
    } catch (e) {
      showToast('网络异常，请稍后重试');
    }
  }, [showToast]);

  // Open group chat by group_id, auto-join if needed
  const openGroupChat = useCallback(async (groupId) => {
    if (!groupId) return;
    try {
      // Try to get group info first
      const res = await API.get(`/im/groups/${groupId}`);
      if (!res.success) {
        showToast(res.message || '打开群聊失败');
        return;
      }
      const group = res.data;
      const uid = currentUser?.id;
      const isMember = group.members?.some(m => m.user_id === uid);
      if (!isMember) {
        // Auto-join
        const joinRes = await API.post(`/im/groups/${groupId}/join`);
        if (!joinRes.success) {
          showToast(joinRes.message || '加入群聊失败');
          return;
        }
      }
      const conv = {
        id: group.id,
        type: 'group',
        name: group.name,
        avatar: '',
        member_count: (group.members || []).length,
      };
      loadConversations();
      openConversation(conv);
    } catch (e) {
      showToast('网络异常，请稍后重试');
    }
  }, [currentUser, loadConversations, showToast]);

  // Auto-open chat from pageParams
  useEffect(() => {
    const target = pageParams?.im?.chatUserId;
    if (target) {
      const name = pageParams.im.chatUserName || '';
      openChatWithUser(target, name);
    }
  }, [pageParams?.im?.chatUserId, openChatWithUser]);

  // Auto-open group chat from pageParams (e.g. from temple)
  useEffect(() => {
    const groupId = pageParams?.im?.groupId;
    if (groupId) {
      openGroupChat(groupId);
    }
  }, [pageParams?.im?.groupId, openGroupChat]);

  const sendMessage = async () => {
    if (!messageInput.trim() || !currentConv) return;
    const content = messageInput.trim();
    setMessageInput('');
    
    try {
      const res = await API.post(`/im/conversations/${currentConv.id}/messages`, { content });
      if (res.success) {
        loadMessages(currentConv.id);
        loadConversations();
      } else {
        showToast(res.message || '发送失败');
        setMessageInput(content);
      }
    } catch (e) {
      showToast('发送失败，请稍后重试');
      setMessageInput(content);
    }
  };

  // Chat detail view
  const renderChatDetail = () => (
    <div style={{
      display: 'flex', flexDirection: 'column',
      position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
      background: 'var(--bg-page)',
      zIndex: 100,
      maxWidth: 480, margin: '0 auto',
    }}>
      {/* Chat Header */}
      <div className="app-header" style={{ position: 'sticky', top: 0, zIndex: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }} onClick={closeChat}>
          <span style={{ fontSize: 20 }}>←</span>
          <div className="avatar avatar-sm" style={{ background: currentConv?.type === 'group' ? '#00B578' : '#3B82F6' }}>
            {currentConv?.name?.charAt(0)}
          </div>
        </div>
        <div style={{ flex: 1, textAlign: 'center', fontWeight: 600 }}>
          {currentConv?.name}
          {currentConv?.type === 'group' && (
            <div style={{ fontSize: 10, color: 'var(--text-tertiary)', fontWeight: 400, marginTop: 1 }}>
              {currentConv?.member_count || 0}人
            </div>
          )}
        </div>
        <div style={{ width: 52, textAlign: 'right', cursor: 'pointer' }} onClick={() => showToast('群设置功能开发中')}>
          {currentConv?.type === 'group' ? '⋯' : ''}
        </div>
      </div>

      {/* Messages */}
      <div style={{ flex: 1, overflowY: 'auto', padding: 16 }}>
        {messages.length === 0 && (
          <div style={{ textAlign: 'center', color: 'var(--text-tertiary)', fontSize: 12, padding: 20 }}>
            暂无消息，开始聊天吧
          </div>
        )}
        {messages.map(msg => {
          if (msg.type === 'system') {
            return (
              <div key={msg.id} style={{
                textAlign: 'center',
                margin: '8px 0',
              }}>
                <span style={{
                  fontSize: 11,
                  color: 'var(--text-tertiary)',
                  background: 'var(--bg-card)',
                  padding: '4px 10px',
                  borderRadius: 10,
                }}>
                  {msg.content}
                </span>
              </div>
            );
          }
          const isMine = msg.sender_id === currentUser?.id || msg.nickname === currentUser?.nickname;
          return (
            <div key={msg.id} style={{
              display: 'flex',
              justifyContent: isMine ? 'flex-end' : 'flex-start',
              marginBottom: 12,
            }}>
              {!isMine && (
                <div className="avatar avatar-sm" style={{ marginRight: 8, background: '#8B5CF6', flexShrink: 0 }}>
                  {(msg.nickname || msg.sender_name || '?').charAt(0)}
                </div>
              )}
              <div style={{ maxWidth: '70%' }}>
                {!isMine && currentConv?.type === 'group' && (
                  <div style={{ fontSize: 10, color: 'var(--text-tertiary)', marginBottom: 2, marginLeft: 2 }}>
                    {msg.nickname || msg.sender_name || ''}
                  </div>
                )}
                <div style={{
                  padding: '10px 14px',
                  borderRadius: isMine ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
                  background: isMine ? 'var(--primary)' : 'var(--bg-card)',
                  color: isMine ? '#fff' : 'var(--text-primary)',
                  fontSize: 14,
                  lineHeight: 1.5,
                  wordBreak: 'break-word',
                }}>
                  {msg.content}
                </div>
              </div>
              {isMine && (
                <div className="avatar avatar-sm" style={{ marginLeft: 8, background: '#3B82F6', flexShrink: 0 }}>
                  {currentUser?.nickname?.charAt(0) || '我'}
                </div>
              )}
            </div>
          );
        })}
        <div ref={msgEndRef}></div>
      </div>

      {/* Input */}
      <div style={{
        padding: '10px 12px',
        paddingBottom: 'calc(10px + env(safe-area-inset-bottom))',
        background: 'var(--bg-card)',
        borderTop: '1px solid var(--border)',
        display: 'flex',
        gap: 8,
        alignItems: 'center',
      }}>
        <input
          className="input"
          style={{ flex: 1 }}
          value={messageInput}
          onChange={(e) => setMessageInput(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') sendMessage(); }}
          placeholder={currentConv?.type === 'group' ? '发消息到群聊...' : '说点什么...'}
        />
        <button className="btn btn-primary" onClick={sendMessage} style={{ padding: '8px 16px' }}>
          发送
        </button>
      </div>
    </div>
  );

  const renderChats = () => (
    <div>
      {conversations.length === 0 && (
        <div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
          暂无会话，去群聊或好友列表开始聊天吧
        </div>
      )}
      {conversations.map(conv => (
        <div key={conv.id + '-' + (conv.type || 'single')} className="im-item" onClick={() => openConversation(conv)}>
          <div className="avatar" style={{ background: conv.type === 'group' ? '#00B578' : '#3B82F6' }}>
            {conv.name?.charAt(0)}
          </div>
          <div className="im-info">
            <div className="flex items-center justify-between">
              <span className="im-name">
                {conv.name}
                {conv.type === 'group' && <span style={{ fontSize: 10, color: 'var(--text-tertiary)', marginLeft: 4 }}>
                  ({conv.member_count || 0})
                </span>}
              </span>
              <span className="im-time">{conv.last_time}</span>
            </div>
            <div className="im-msg">{conv.last_message || '暂无消息'}</div>
          </div>
        </div>
      ))}
    </div>
  );

  const renderGroups = () => (
    <div>
      <div style={{ padding: '10px 16px', background: 'var(--bg-card)', borderBottom: '1px solid var(--border)' }}>
        <div style={{
          background: 'var(--bg-page)',
          borderRadius: 8,
          padding: '8px 12px',
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          color: 'var(--text-tertiary)',
          fontSize: 13,
        }}>
          <span>🔍</span>
          <span>搜索群聊</span>
        </div>
      </div>

      <div className="im-item" onClick={() => showToast('功能开发中，敬请期待')}>
        <div style={{
          width: 40, height: 40, borderRadius: '50%',
          background: 'var(--primary-light)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 20, color: 'var(--primary)',
        }}>＋</div>
        <div className="im-info">
          <div className="im-name" style={{ color: 'var(--primary)' }}>创建新群聊</div>
          <div className="im-msg">邀请好友一起聊天</div>
        </div>
      </div>

      {groups.length === 0 && (
        <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
          还没有加入任何群聊
        </div>
      )}
      {groups.map(group => (
        <div key={group.id} className="im-item" onClick={() => openGroupChat(group.id)}>
          <div className="avatar" style={{ background: '#00B578' }}>{group.name?.charAt(0)}</div>
          <div className="im-info">
            <div className="flex items-center justify-between">
              <span className="im-name">{group.name}</span>
              <span className="im-time"></span>
            </div>
            <div className="im-msg">{group.member_count}人</div>
          </div>
        </div>
      ))}
    </div>
  );

  const renderContacts = () => (
    <div>
      <div style={{ padding: '10px 16px', background: 'var(--bg-card)', borderBottom: '1px solid var(--border)' }}>
        <div style={{
          background: 'var(--bg-page)',
          borderRadius: 8,
          padding: '8px 12px',
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          color: 'var(--text-tertiary)',
          fontSize: 13,
        }}>
          <span>🔍</span>
          <span>搜索好友</span>
        </div>
      </div>

      <div style={{ background: 'var(--bg-card)', marginBottom: 8 }}>
        <div className="im-item" onClick={() => showToast('功能开发中，敬请期待')}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%',
            background: '#3B82F6',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 20, color: '#fff',
          }}>👤</div>
          <div className="im-info">
            <div className="im-name">新的朋友</div>
            <div className="im-msg">添加好友</div>
          </div>
        </div>
        <div className="im-item" onClick={() => setActiveTab('groups')}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%',
            background: '#00B578',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 20, color: '#fff',
          }}>👥</div>
          <div className="im-info">
            <div className="im-name">群聊</div>
            <div className="im-msg">{groups.length}个群</div>
          </div>
        </div>
      </div>

      <div style={{ background: 'var(--bg-card)' }}>
        <div style={{ padding: '8px 16px', fontSize: 12, color: 'var(--text-tertiary)' }}>
          好友 · {friends.length}
        </div>
        {friends.map(friend => (
          <div key={friend.friend_id} className="im-item" onClick={() => openFriendChat(friend)}>
            <div className="avatar" style={{ background: '#8B5CF6' }}>
              {friend.nickname?.charAt(0)}
            </div>
            <div className="im-info">
              <div className="im-name">{friend.nickname}</div>
              <div className="im-msg">久聊号: {friend.jiuLiaoId}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  const renderMe = () => (
    <div>
      <div style={{
        background: 'linear-gradient(135deg, #3B82F6 0%, #60A5FA 100%)',
        padding: '20px 16px',
        color: '#fff',
        display: 'flex',
        alignItems: 'center',
        gap: 12,
      }}>
        <div className="avatar avatar-xl" style={{ background: '#fff', color: '#3B82F6', fontSize: 32 }}>
          {currentUser?.nickname?.charAt(0) || '我'}
        </div>
        <div className="flex-1">
          <div style={{ fontSize: 18, fontWeight: 600 }}>{currentUser?.nickname || '用户'}</div>
          <div style={{ fontSize: 12, opacity: 0.9, marginTop: 4 }}>久聊号: {currentUser?.jiuLiaoId || '10001'}</div>
          <div style={{ display: 'inline-block', marginTop: 6, padding: '2px 8px', background: 'rgba(255,255,255,0.2)', borderRadius: 10, fontSize: 10 }}>
            📋 我的二维码
          </div>
        </div>
        <span style={{ fontSize: 18 }}>⚙️</span>
      </div>

      <div className="card card-shadow" style={{ margin: 12 }}>
        <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 10 }}>久聊号说明</div>
        <div style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.8 }}>
          • 个人久聊号从 <strong>10000</strong> 起始<br/>
          • 企业久聊号以 <strong>B+10000</strong> 起始<br/>
          • 支持靓号市场，选择心仪号码<br/>
          • 名片分享裂变，邀请好友得奖励
        </div>
        <button className="btn btn-ghost btn-block" style={{ marginTop: 10 }} onClick={() => navigate('member')}>
          逛逛靓号市场 →
        </button>
      </div>

      <div className="card card-shadow" style={{ margin: 12, padding: 0 }}>
        <div className="list-item" onClick={() => navigate('member')}>
          <span style={{ fontSize: 20, marginRight: 12 }}>👑</span>
          <span className="flex-1">会员中心</span>
          <span style={{ color: 'var(--text-tertiary)' }}>→</span>
        </div>
        <div className="list-item" onClick={() => showToast('功能开发中，敬请期待')}>
          <span style={{ fontSize: 20, marginRight: 12 }}>⭐</span>
          <span className="flex-1">我的收藏</span>
          <span style={{ color: 'var(--text-tertiary)' }}>→</span>
        </div>
        <div className="list-item" onClick={() => showToast('功能开发中，敬请期待')}>
          <span style={{ fontSize: 20, marginRight: 12 }}>📷</span>
          <span className="flex-1">我的相册</span>
          <span style={{ color: 'var(--text-tertiary)' }}>→</span>
        </div>
        <div className="list-item" style={{ borderBottom: 'none' }} onClick={() => showToast('功能开发中，敬请期待')}>
          <span style={{ fontSize: 20, marginRight: 12 }}>⚙️</span>
          <span className="flex-1">设置</span>
          <span style={{ color: 'var(--text-tertiary)' }}>→</span>
        </div>
      </div>
    </div>
  );

  return (
    <PageWrapper>
      <AppHeader
        title="久聊"
        subtitle="即时通讯"
        showBack
        onBack={() => currentConv ? closeChat() : goBack()}
        rightContent={<span style={{ fontSize: 20, cursor: 'pointer' }} onClick={() => showToast('功能开发中，敬请期待')}>➕</span>}
      />
      
      {currentConv ? renderChatDetail() : (
        <>
          {activeTab === 'chats' && renderChats()}
          {activeTab === 'groups' && renderGroups()}
          {activeTab === 'contacts' && renderContacts()}
          {activeTab === 'me' && renderMe()}
        </>
      )}

    </PageWrapper>
  );
}

Object.assign(window, { IMPage });
