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

const DEFAULT_AVATAR_URL = `${process.env.PUBLIC_URL}/default-avatar.png`;

const UserProfile = () => {
  const { user, loading } = useUser();
  const [userProfile, setUserProfile] = useState(null);
  const [error, setError] = useState(null);

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

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

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

        const profile = {
          avatarUrl: raw.avatarUrl
            ? `${process.env.REACT_APP_AVATAR_BASE_URL}${raw.avatarUrl}`
            : DEFAULT_AVATAR_URL,
          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,
          uploadAmount: raw.uploadCount ?? 0,
          downloadAmount: raw.downloadCount ?? 0,
          shareRate: raw.shareRate ?? 0,
          joinedDate: raw.registrationTime,
        };

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

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

  const handleAvatarUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      const { data } = await axios.post(
        `/echo/user/${user.userId}/uploadAvatar`,
        formData,
        { headers: { 'Content-Type': 'multipart/form-data' } }
      );

      if (data?.avatarUrl) {
        setUserProfile((prev) => ({
          ...prev,
          avatarUrl: `${process.env.REACT_APP_AVATAR_BASE_URL}${data.avatarUrl}`,
        }));
        alert('头像上传成功');
      } else {
        alert('头像上传成功，但未返回新头像地址');
      }
    } catch (err) {
      console.error('上传失败:', err);
      alert('头像上传失败，请重试');
    }
  };

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

  const {
    avatarUrl,
    nickname,
    email,
    gender,
    bio,
    interests,
    level,
    experience,
    uploadAmount,
    downloadAmount,
    shareRate,
    joinedDate,
  } = userProfile;

  return (
    <div className="common-card">
      <div className="right-content">
        <div className="profile-header">
          <div className="avatar-wrapper">
            <img src={avatarUrl} alt={nickname} className="avatar" />
            <label htmlFor="avatar-upload" className="avatar-upload-label">
              上传头像
            </label>
            <input
              type="file"
              id="avatar-upload"
              accept="image/*"
              style={{ display: 'none' }}
              onChange={handleAvatarUpload}
            />
          </div>
          <h1>{nickname}</h1>
        </div>

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

export default UserProfile;

