//TrocardePerfis.jsx
//Nesta página falta: ajustar caminho do CSS

import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { UserInfos } from "../_assets/utils/Functions-Endpoints/General";
import { useAuth } from "../_assets/utils/AuthProvider";

//import "./TrocardePerfis.css";

const ToggleIcon = ({ isOpen }) => (
  <svg 
    xmlns="http://www.w3.org/2000/svg" 
    width="20" 
    height="20" 
    viewBox="0 0 24 24" 
    fill="none" 
    stroke="currentColor" 
    strokeWidth="2" 
    strokeLinecap="round" 
    strokeLinejoin="round"
    style={{ transition: 'transform 0.3s', transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}
  >
    <polyline points="6 9 12 15 18 9"></polyline>
  </svg>
);


const TrocardePerfis = () => {
  const navigate = useNavigate();
  const { getAuthorizationHeader } = useAuth();

  const [showProfiles, setShowProfiles] = useState([]);
  const [isOpen, setIsOpen] = useState(false); 

  useEffect(() => {
    const fetchData = async () => {
      const authHeader = getAuthorizationHeader();
      try {
        const userInfo = await UserInfos(authHeader);
        setShowProfiles(userInfo?.roles || []);
      } catch (error) {
        console.error("Erro ao buscar informações do usuário:", error);
        setShowProfiles([]);
      }
    };
    fetchData();
  }, [getAuthorizationHeader]);

  const handleProfileClick = (route) => {
    if (route) {
      navigate(route);
      setIsOpen(false); 
    }
  };


  const handleToggle = () => {
    setIsOpen(prev => !prev);
  };

  const options = [
    { key: "secretaria", label: "Secretaria", route: "/secretaria" },
    { key: "medico", label: "Médico", route: "/medico" },
    { key: "financeiro", label: "Financeiro", route: "/financeiro" },
    { key: "admin", label: "Administração", route: "/admin" },
    { key: "paciente", label: "Paciente", route: "/paciente" },
  ].filter(
    (opt) =>
      showProfiles?.includes(opt.key) || showProfiles?.includes("admin")
  );

  return (
    <div className="container-perfis-toggle">
      
      <div 
        className="toggle-button"
        onClick={handleToggle}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            handleToggle();
          }
        }}
      >
        <span className="acesso-text">Acesso aos módulos</span>
        <ToggleIcon isOpen={isOpen} />
      </div>

      {isOpen && (
        <div className="perfil-list"> 
          {options.length > 0 ? (
            options.map((opt) => (
              <div
                key={opt.key}
                className="perfil-item"
                onClick={() => handleProfileClick(opt.route)}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    handleProfileClick(opt.route);
                  }
                }}
              >
                {opt.label}
              </div>
            ))
          ) : (
            <p className="no-profiles">Nenhum perfil disponível.</p>
          )}
        </div>
      )}
    </div>
  );
};

export default TrocardePerfis;