import { MessageOutlined } from '@ant-design/icons';
import { Tag, List, Button, Space, message } from 'antd';
import type { FC } from 'react';
import { useMemo, useState } from 'react';
import { acceptFriendRequest, queryHistoryMessages, rejectFriendRequest } from '../../service';
import type { HistoryMessage, MessageItem, WebSocketMessage } from '../../data';
import { useRequest } from '@umijs/max';


type MessageParams = {
  messages: WebSocketMessage[];
  sendChatMessage: (toUserId: string, content: string) => void;
}

// 消息 Tab：基于 WebSocket 的好友请求 & 聊天消息展示
const Messages: FC<MessageParams> = (props) => {
  const { messages: wsMessages, sendChatMessage } = props;
  const [localMessages, setLocalMessages] = useState<MessageItem[]>([]);

  const { data: historyResp } = useRequest(() => queryHistoryMessages());

  const historyMessages: MessageItem[] = useMemo(() => {
    const list = ((historyResp) || []) as HistoryMessage[];
    return list.map((m) => {
      const isFriendRequest = m.category === 'friend' && m.type === 'friend_request';
      const base = {
        id: String(m.id),
        category: m.category,
        senderId: m.fromUserId,
        senderName: m.title || m.fromUserId,
        content:
          m.content ||
          (m.type === 'friend_accept'
            ? '你的好友请求已被接受'
            : m.type === 'friend_reject'
            ? '你的好友请求已被拒绝'
            : ''),
        toUserId: m.toUserId,
      };

      if (isFriendRequest) {
        return {
          ...base,
          type: 'friend_request' as const,
          status: m.status === 'unread' ? 'pending' : 'accepted',
        };
      }

      return {
        ...base,
        type: 'friend_message' as const,
        status: 'read',
      };
    });
  }, [historyResp]);
  console.log(historyMessages);
  
  const wsMapped: MessageItem[] = useMemo(() => {
    return wsMessages
      .map((m, index) => {
        if (m.type === 'friend') {
          const isRequest = m.subType === 'friend_request';
          const base = {
            id: `ws-friend-${index}`,
            category: 'friend',
            senderId: m.fromUserId || m.senderId || '',
            senderName: m.senderName || m.title || '好友',
            content:
              m.content ||
              (m.subType === 'friend_accept'
                ? '你的好友请求已被接受'
                : m.subType === 'friend_reject'
                ? '你的好友请求已被拒绝'
                : ''),
            toUserId: m.toUserId || '',
          };
          if (isRequest) {
            return {
              ...base,
              type: 'friend_request' as const,
              status: 'pending' as const,
            };
          }
          return {
            ...base,
            type: 'friend_message' as const,
            status: 'read' as const,
          };
        }
        if (m.type === 'chat') {
          return {
            id: `ws-chat-${index}`,
            type: 'friend_message' as const,
            category: 'chat',
            senderId: m.senderId || m.fromUserId || '',
            senderName: m.senderName || '好友',
            content: m.content || '',
            status: 'read' as const,
            toUserId: m.toUserId || '',
          };
        }
        return null;
      })
      .filter(Boolean) as MessageItem[];
  }, [wsMessages]);

  const allMessages: MessageItem[] = useMemo(
    () => [...historyMessages, ...wsMapped, ...localMessages],
    [historyMessages, wsMapped, localMessages],
  );

  const updateStatus = (id: string, status: Exclude<MessageItem['status'], undefined>) => {
    setLocalMessages((prev) =>
      prev.map((m) => (m.id === id ? { ...m, status } : m)) as MessageItem[],
    );
  };

  const handleReply = (msg: Extract<MessageItem, { type: 'friend_message' }>) => {
    const reply = window.prompt(`回复 ${msg.senderName}:`, '');
    console.log(msg);
    
    if (!reply) return;
    if (!msg.senderId) {
      message.error('缺少对方用户ID，无法发送消息');
      return;
    }
    sendChatMessage(msg.senderId, reply);
    message.success('已发送回复');
  };

  const handleAccept = async (msg: Extract<MessageItem, { type: 'friend_request' }>) => {
    try {
      await acceptFriendRequest(msg.senderId);
      message.success('已接受好友请求');
      updateStatus(msg.id, 'accepted');
    } catch (e: any) {
      message.error(e?.message || '接受失败');
    }
  };

  const handleReject = async (msg: Extract<MessageItem, { type: 'friend_request' }>) => {
    try {
      await rejectFriendRequest(msg.senderId);
      message.info('已拒绝好友请求');
      updateStatus(msg.id, 'rejected');
    } catch (e: any) {
      message.error(e?.message || '拒绝失败');
    }
  };

  return (
    <List
      itemLayout="vertical"
      dataSource={allMessages}
      locale={{ emptyText: '暂无消息' }}
      renderItem={(item) => (
        <List.Item
          key={item.id}
          actions={[
            item.type === 'friend_request' && item.status === 'pending' ? (
              <Space key="actions">
                <Button size="small" type="primary" onClick={() => handleAccept(item)}>
                  接受
                </Button>
                <Button size="small" danger onClick={() => handleReject(item)}>
                  拒绝
                </Button>
              </Space>
            ) : item.type === 'friend_message' ? (
              <Button
                key="reply"
                size="small"
                icon={<MessageOutlined />}
                onClick={() => handleReply(item)}
              >
                回复
              </Button>
            ) : null,
          ]}
        >
          <List.Item.Meta
            title={`${item.senderName} ${item.type === 'friend_request' ? '的好友请求' : '的消息'}`}
            description={item.content}
          />
          {item.status && <Tag color="blue">状态：{item.status}</Tag>}
        </List.Item>
      )}
    />
  );
};
export default Messages;