import React, { useEffect, useState } from 'react';
import './MessagePage.css';
import { useUser } from '../../context/UserContext';

const API_BASE = process.env.REACT_APP_API_BASE;

const mockMessages = [
  {
    message_id: 1,
    sender_username: 'Alice',
    timestamp: Date.now() - 100000,
    content: '你好，这是测试消息。',
  },
  {
    message_id: 2,
    sender_username: 'Bob',
    timestamp: Date.now() - 50000,
    content: '欢迎使用我们的平台！',
  },
];

const MessagePage = () => {
  const { user } = useUser(); // 从上下文中获取用户
  const currentUserId = user?.id;

  const [messages, setMessages] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (currentUserId) {
      fetchMessages();
    }
  }, [currentUserId]);

  const fetchMessages = async () => {
    setLoading(true);
    try {
      if (process.env.NODE_ENV === 'development') {
        await new Promise((r) => setTimeout(r, 500)); // 模拟延迟
        setMessages(mockMessages);
      } else {
        const response = await fetch(`${API_BASE}/echo/messages/${currentUserId}`);
        const data = await response.json();
        if (data.status === 'success') {
          setMessages(data.messages);
        } else {
          setMessages([]);
        }
      }
    } catch (error) {
      console.error('加载消息失败:', error);
      setMessages([]);
    } finally {
      setLoading(false);
    }
  };

  if (!currentUserId) {
    return <div className="message-page">未登录，无法加载消息。</div>;
  }

  if (loading) {
    return <div className="message-page">加载中...</div>;
  }

  return (
    <div className="message-page">
      <h2>我的消息</h2>
      {messages.length === 0 ? (
        <div>暂无消息记录</div>
      ) : (
        <ul className="message-list">
          {messages.map((msg) => (
            <li key={msg.message_id} className="message-item">
              <div className="message-header">
                来自：<strong>{msg.sender_username}</strong>
                <span className="message-time">
                  {new Date(msg.timestamp).toLocaleString()}
                </span>
              </div>
              <div className="message-content">
                {msg.content}
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default MessagePage;
