import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { notificationApi } from '../../api/notification';
import './personalSubpage.css';

const Notice = ({ onLogout }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [notices, setNotices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 获取当前用户ID（根据你的实际应用获取方式）
  const userId = localStorage.getItem('username') || 'default-user-id';

  // 获取通知列表
  const fetchNotifications = async () => {
    try {
      setLoading(true);
      const response = await notificationApi.getNotifications(userId);
      setNotices(response.data.notifications || []);
    } catch (err) {
      setError('获取通知失败，请稍后重试');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchNotifications();
  }, [userId]);

  const handleBack = () => {
    navigate('/personal', { 
      state: { 
        fromSubpage: true,
        dashboardTab: location.state?.dashboardTab
      },
      replace: true
    });
  };

  // 标记为已读处理
  const handleMarkAsRead = async (id) => {
    try {
      const result = await notificationApi.markNotificationAsRead(id);
      
      if (result.success) {
        // 使用后端返回的更新后通知替换本地状态
        setNotices(prevNotices => 
          prevNotices.map(notice => 
            notice.id === id ? result.notification : notice
          )
        );
      } else {
        setError(result.message || '标记为已读失败');
      }
    } catch (err) {
      console.error('标记为已读失败:', err);
      setError('标记为已读失败，请稍后重试');
    }
  };

  const handleItemClick = (notice) => {
    if (!notice.isRead) {
      handleMarkAsRead(notice.id);
    }
    // 这里可以添加其他点击逻辑，比如展开详情等
  };

  return (
    <div className="subpage-container">
      <button className="back-button" onClick={handleBack}>
      返回个人中心
      </button>

      <h2 className="page-title">消息通知</h2>
      
      {loading && <div className="loading-message">加载中...</div>}
      {error && <div className="error-message">{error}</div>}
      
      <div className="notice-list">
        {notices.length === 0 && !loading ? (
          <div className="empty-notice">暂无通知</div>
        ) : (
          notices.map(notice => (
            <div 
              key={notice.id} 
              className={`list-item ${!notice.isRead ? 'unread' : ''}`}
              onClick={() => handleItemClick(notice)}
            >
              <div className="notice-header">
                <h3>{notice.title}</h3>
                <span className="notice-date">
                  {new Date(notice.date).toLocaleDateString()}
                  {!notice.isRead && <span className="unread-badge">未读</span>}
                </span>
              </div>
              <p className="notice-content">{notice.content}</p>
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default Notice;