import { api } from '@/services/api';
import { auth } from '@/services/auth';
import { useEffect, useState } from 'react';
import './index.css';

interface UserInfoProps {
  className?: string;
}

export default function UserInfo({ className }: UserInfoProps) {
  const [userInfo, setUserInfo] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadUserInfo = async () => {
      try {
        const info = await api.profile();
        setUserInfo(info);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadUserInfo();
  }, []);

  const handleLogout = async () => {
    if (confirm('确定要退出登录吗？')) {
      await auth.logout();
      window.location.reload();
    }
  };

  if (loading) {
    return (
      <div className={`user-info ${className || ''}`}>
        <div className="user-info-loading">加载中...</div>
      </div>
    );
  }

  if (!userInfo) {
    return null;
  }

  return (
    <div className={`user-info ${className || ''}`}>
      <div className="user-avatar">
        {userInfo.picture ? (
          <img src={userInfo.picture} alt="用户头像" />
        ) : (
          <div className="avatar-placeholder">{userInfo.name?.charAt(0) || 'U'}</div>
        )}
      </div>
      <div className="user-details">
        <div className="user-name">{userInfo.name || '未知用户'}</div>
        <div className="user-email">{userInfo.email || ''}</div>
      </div>
      <button className="logout-button" onClick={handleLogout}>
        退出
      </button>
    </div>
  );
}
