import React from 'react';
import { useNavigate } from 'react-router-dom';
import { LogOut, Settings, LayoutDashboard } from 'lucide-react';
import { useAuth } from '../../hooks/useAuth';

export function ProfileMenu() {
  const { user, userRole, signOut } = useAuth();
  const navigate = useNavigate();
  const [isOpen, setIsOpen] = React.useState(false);
  const menuRef = React.useRef<HTMLDivElement>(null);

  // Fecha o menu quando clicar fora dele
  React.useEffect(() => {
    function 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 getDashboardPath = () => {
    switch (userRole) {
      case 'school':
        return '/dashboard';
      case 'teacher':
        return '/professor';
      case 'student':
        return '/aluno';
      default:
        return '/';
    }
  };

  const getProfilePath = () => {
    switch (userRole) {
      case 'school':
        return '/dashboard/configuracoes';
      case 'teacher':
        return '/professor/perfil';
      case 'student':
        return '/aluno/perfil';
      default:
        return '/';
    }
  };

  return (
    <div className="relative" ref={menuRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center hover:bg-purple-200 transition"
      >
        <span className="text-lg font-medium text-purple-600">
          {user?.user_metadata?.name?.[0]?.toUpperCase() || user?.email?.[0]?.toUpperCase()}
        </span>
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-1 border border-gray-200">
          <button
            onClick={() => {
              navigate(getDashboardPath());
              setIsOpen(false);
            }}
            className="w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 flex items-center gap-2"
          >
            <LayoutDashboard className="h-4 w-4" />
            Acessar Dashboard
          </button>
          
          <button
            onClick={() => {
              navigate(getProfilePath());
              setIsOpen(false);
            }}
            className="w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100 flex items-center gap-2"
          >
            <Settings className="h-4 w-4" />
            Meu Perfil
          </button>
          
          <hr className="my-1" />
          
          <button
            onClick={signOut}
            className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-gray-100 flex items-center gap-2"
          >
            <LogOut className="h-4 w-4" />
            Sair
          </button>
        </div>
      )}
    </div>
  );
} 