import React, { useState, useEffect, useRef } from "react";
import { LogIn, User, LogOut, ChevronDown } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";

export type ProfileType = "patient" | "doctor" | "secretary" | null;

export const ProfileSelector: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated, user, logout } = useAuth();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Fechar dropdown ao clicar fora
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

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

  // Se o usuário NÃO estiver autenticado, mostra botão de login
  if (!isAuthenticated || !user) {
    return (
      <button
        onClick={() => navigate("/login")}
        className="flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium transition-all text-white bg-blue-600 hover:bg-blue-700 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
        aria-label="Fazer Login"
      >
        <LogIn className="w-4 h-4" aria-hidden="true" />
        <span>Fazer Login</span>
      </button>
    );
  }

  // Se o usuário ESTIVER autenticado, mostra menu de perfil
  const isAdmin = user.role === "admin" || user.role === "gestor";

  const handleNavigateToDashboard = () => {
    setIsOpen(false);
    if (isAdmin) {
      navigate("/admin");
      return;
    }
    switch (user.role) {
      case "paciente":
        navigate("/acompanhamento");
        break;
      case "medico":
        navigate("/painel-medico");
        break;
      case "secretaria":
        navigate("/painel-secretaria");
        break;
      default:
        navigate("/");
    }
  };

  const handleLogout = () => {
    setIsOpen(false);
    logout();
    navigate("/");
  };

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center space-x-2 px-4 py-2 rounded-lg text-sm font-medium transition-all text-gray-700 bg-gray-100 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
        aria-label="Menu do usuário"
      >
        <User className="w-4 h-4" aria-hidden="true" />
        <span>{user.nome}</span>
        <ChevronDown
          className={`w-4 h-4 transition-transform ${
            isOpen ? "rotate-180" : ""
          }`}
          aria-hidden="true"
        />
      </button>

      {isOpen && (
        <div className="absolute right-0 mt-2 w-56 bg-white rounded-lg shadow-xl border border-gray-200 z-[9999] pointer-events-auto">
          {isAdmin ? (
            <>
              <button
                onClick={() => {
                  setIsOpen(false);
                  navigate("/admin");
                }}
                className="w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-purple-50 hover:text-purple-700 rounded-t-lg flex items-center space-x-2 cursor-pointer transition-colors"
              >
                <User className="w-4 h-4" />
                <span>Painel Admin</span>
              </button>
              <div className="border-t border-gray-100"></div>
              <div className="px-3 py-1.5 text-xs font-semibold text-gray-500 uppercase">
                Acessar como:
              </div>
              <button
                onClick={() => {
                  setIsOpen(false);
                  navigate("/painel-medico");
                }}
                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700 flex items-center space-x-2 cursor-pointer transition-colors"
              >
                <span>👨‍⚕️</span>
                <span>Médico</span>
              </button>
              <button
                onClick={() => {
                  setIsOpen(false);
                  navigate("/painel-secretaria");
                }}
                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-green-50 hover:text-green-700 flex items-center space-x-2 cursor-pointer transition-colors"
              >
                <span>👩‍💼</span>
                <span>Secretária</span>
              </button>
              <button
                onClick={() => {
                  setIsOpen(false);
                  navigate("/acompanhamento");
                }}
                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-indigo-50 hover:text-indigo-700 flex items-center space-x-2 cursor-pointer transition-colors"
              >
                <span>🧑‍🦱</span>
                <span>Paciente</span>
              </button>
              <div className="border-t border-gray-100"></div>
            </>
          ) : (
            <>
              <button
                onClick={handleNavigateToDashboard}
                className="w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-100 rounded-t-lg flex items-center space-x-2 cursor-pointer"
              >
                <User className="w-4 h-4" />
                <span>Meu Painel</span>
              </button>
              <div className="border-t border-gray-100"></div>
            </>
          )}
          <button
            onClick={handleLogout}
            className="w-full text-left px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 rounded-b-lg flex items-center space-x-2 cursor-pointer"
          >
            <LogOut className="w-4 h-4" />
            <span>Sair</span>
          </button>
        </div>
      )}
    </div>
  );
};

export default ProfileSelector;
