/**
 * 用户菜单组件
 * 显示用户头像、信息和操作菜单
 */

import React, { useState, useRef, useEffect } from 'react';
import { 
  User, 
  Settings, 
  LogOut, 
  ChevronDown,
  Shield,
  Edit3
} from 'lucide-react';
import { useAuthStore } from '../stores/useAuthStore';
import { useNavigate } from 'react-router-dom';

const UserMenu: React.FC = () => {
  const { user, logout } = useAuthStore();
  const navigate = useNavigate();
  const [isOpen, setIsOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleLogout = async () => {
    try {
      await logout();
      navigate('/login');
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  const getAvatarUrl = () => {
    if (user?.avatarUrl) {
      return user.avatarUrl;
    }
    // 生成基于用户名的头像
    const name = user?.displayName || user?.username || 'User';
    return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=2563eb&color=ffffff&size=40`;
  };

  const getUserInitials = () => {
    const name = user?.displayName || user?.username || 'User';
    return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
  };

  if (!user) {
    return null;
  }

  return (
    <div className="relative" ref={menuRef}>
      {/* 用户头像按钮 */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center space-x-3 p-2 rounded-lg hover:bg-secondary-100 transition-colors focus:outline-none focus:ring-2 focus:ring-primary-500"
      >
        <div className="relative">
          <img
            src={getAvatarUrl()}
            alt={user.displayName || user.username}
            className="w-8 h-8 rounded-full object-cover"
            onError={(e) => {
              // 如果头像加载失败，显示文字头像
              const target = e.target as HTMLImageElement;
              target.style.display = 'none';
              const parent = target.parentElement;
              if (parent) {
                const fallback = document.createElement('div');
                fallback.className = 'w-8 h-8 rounded-full bg-primary-500 flex items-center justify-center text-white text-sm font-semibold';
                fallback.textContent = getUserInitials();
                parent.appendChild(fallback);
              }
            }}
          />
          <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 border-2 border-white rounded-full"></div>
        </div>
        
        <div className="hidden md:block text-left">
          <p className="text-sm font-medium text-secondary-900">{user.displayName || user.username}</p>
          <p className="text-xs text-secondary-500">{user.email}</p>
        </div>
        
        <ChevronDown className={`w-4 h-4 text-secondary-500 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {/* 下拉菜单 */}
      {isOpen && (
        <div className="absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border border-secondary-200 py-2 z-50">
          {/* 用户信息 */}
          <div className="px-4 py-3 border-b border-secondary-200">
            <div className="flex items-center space-x-3">
              <img
                src={getAvatarUrl()}
                alt={user.displayName || user.username}
                className="w-10 h-10 rounded-full object-cover"
              />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-secondary-900 truncate">
                  {user.displayName || user.username}
                </p>
                <p className="text-xs text-secondary-500 truncate">{user.email}</p>
                <div className="flex items-center mt-1">
                  <Shield className="w-3 h-3 text-green-500 mr-1" />
                  <span className="text-xs text-green-600">已验证</span>
                </div>
              </div>
            </div>
          </div>

          {/* 菜单项 */}
          <div className="py-2">
            <button
              onClick={() => {
                setIsOpen(false);
                navigate('/profile');
              }}
              className="w-full flex items-center px-4 py-2 text-sm text-secondary-700 hover:bg-secondary-50 transition-colors"
            >
              <User className="w-4 h-4 mr-3" />
              个人资料
            </button>
            
            <button
              onClick={() => {
                setIsOpen(false);
                navigate('/profile/edit');
              }}
              className="w-full flex items-center px-4 py-2 text-sm text-secondary-700 hover:bg-secondary-50 transition-colors"
            >
              <Edit3 className="w-4 h-4 mr-3" />
              编辑资料
            </button>
            
            <button
              onClick={() => {
                setIsOpen(false);
                navigate('/settings');
              }}
              className="w-full flex items-center px-4 py-2 text-sm text-secondary-700 hover:bg-secondary-50 transition-colors"
            >
              <Settings className="w-4 h-4 mr-3" />
              设置
            </button>
          </div>

          {/* 分割线 */}
          <div className="border-t border-secondary-200 my-2"></div>

          {/* 登出 */}
          <button
            onClick={() => {
              setIsOpen(false);
              handleLogout();
            }}
            className="w-full flex items-center px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors"
          >
            <LogOut className="w-4 h-4 mr-3" />
            退出登录
          </button>
        </div>
      )}
    </div>
  );
};

export default UserMenu;
