import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './UserProfile.css';
import UserNav from './UserNav';
import Header from '../../components/Header';
import { useUser } from '../../context/UserContext'; 

const UserProfile = () => {
  const { user, loading } = useUser(); // 从上下文拿用户和加载状态
  const [userProfile, setUserProfile] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (loading) return; // 用户信息还没加载完，先不请求
    console.log('用户:', user, '加载:', loading);

    if (!user || !user.userId) {
      setError('未登录或用户信息缺失');
      setUserProfile(null);
      return;
    }

    const fetchUserProfile = async () => {
      try {
        setError(null);
        const response = await axios.get(`/echo/user/${user.userId}/getProfile`);

        console.log('响应数据:', response); // 调试用
        const raw = response.data;
        console.log('raw:', raw); // 调试用

        if (!raw) {
          setError('用户数据为空');
          setUserProfile(null);
          return;
        }

        const profile = {
          avatar_url: raw.avatarUrl || 'https://example.com/default-avatar.jpg',
          nickname: raw.username || '未知用户',
          email: raw.email || '未填写',
          gender: raw.gender || '保密',
          bio: raw.description || '无',
          interests: raw.hobbies ? raw.hobbies.split(',') : [],
          level: raw.level || '未知',
          experience: raw.experience ?? 0,
          upload_amount: raw.uploadCount ?? 0,
          download_amount: raw.downloadCount ?? 0,
          share_rate: raw.shareRate ?? 0,
          joined_date: raw.registrationTime,
        };

        setUserProfile(profile);
      } catch (err) {
        if (err.response?.status === 404) {
          setError('用户不存在');
        } else {
          setError('请求失败，请稍后再试');
        }
        setUserProfile(null);
      }
    };

    fetchUserProfile();
  }, [user, loading]);

  if (loading) return <p>正在加载用户信息...</p>;
  if (error) return <p className="error">{error}</p>;
  if (!userProfile) return null;

  return (
    <div className="user-profile-container">
      <Header />
      <div className="user-center">
        <div className="user-nav-container">
          <UserNav />
        </div>
        <div className="common-card">
          <div className="right-content">
            <div className="profile-header">
              <img
                src={userProfile.avatar_url}
                alt={userProfile.nickname}
                className="avatar"
              />
              <h1>{userProfile.nickname}</h1>
            </div>

            <div className="profile-details">
              <p><strong>邮箱：</strong>{userProfile.email}</p>
              <p><strong>性别：</strong>{userProfile.gender}</p>
              <p><strong>个人简介：</strong>{userProfile.bio}</p>
              <p><strong>兴趣：</strong>{userProfile.interests.length > 0 ? userProfile.interests.join(', ') : '无'}</p>
              <p><strong>等级：</strong>{userProfile.level}</p>
              <p><strong>经验：</strong>{userProfile.experience}</p>
              <p><strong>上传量：</strong>{userProfile.upload_amount}</p>
              <p><strong>下载量：</strong>{userProfile.download_amount}</p>
              <p><strong>分享率：</strong>{(userProfile.share_rate * 100).toFixed(2)}%</p>
              <p><strong>加入时间：</strong>{new Date(userProfile.joined_date).toLocaleDateString()}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UserProfile;
