import React, { useState, useEffect, useCallback } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import "./style/ProfilePage.css";

const ROLES = {
  ADMIN: "Administrador",
  SECRETARY: "Secretária",
  DOCTOR: "Médico",
  FINANCIAL: "Financeiro"
};

const ProfilePage = () => {
  const location = useLocation();
  const navigate = useNavigate();

  const getRoleFromPath = useCallback(() => {
    const path = location.pathname;
    if (path.includes("/admin")) return ROLES.ADMIN;
    if (path.includes("/secretaria")) return ROLES.SECRETARY;
    if (path.includes("/medico")) return ROLES.DOCTOR;
    if (path.includes("/financeiro")) return ROLES.FINANCIAL;
    return "Usuário";
  }, [location.pathname]);

  const userRole = getRoleFromPath();

  const [userName, setUserName] = useState("Admin Padrão");
  const [userEmail, setUserEmail] = useState("admin@squad23.com");
  const [avatarUrl, setAvatarUrl] = useState(null);
  const [isEditingName, setIsEditingName] = useState(false);
  const [error, setError] = useState(null);


  useEffect(() => {
    const handleEscKey = (event) => {
      if (event.keyCode === 27) handleClose();
    };

    document.addEventListener('keydown', handleEscKey);
    return () => document.removeEventListener('keydown', handleEscKey);
  }, []);


  useEffect(() => {
    const loadProfileData = () => {
      const localAvatar = localStorage.getItem('user_avatar');
      if (localAvatar) {
        setAvatarUrl(localAvatar);
      }
    };

    loadProfileData();

   
    const handleStorageChange = () => {
      loadProfileData();
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  const handleNameSave = () => {
    if (userName.trim() === "") {
      setError("Nome não pode estar vazio");
      return;
    }

    setIsEditingName(false);
    setError(null);
  };

  const handleNameKeyDown = (event) => {
    if (event.key === "Enter") handleNameSave();
    if (event.key === "Escape") {
      setUserName("Admin Padrão");
      setIsEditingName(false);
      setError(null);
    }
  };

  const handleClose = () => navigate(-1);

  return (
    <div className="profile-overlay" role="dialog" aria-modal="true">
      <div className="profile-modal">
        <button
          className="profile-close"
          onClick={handleClose}
          aria-label="Fechar Perfil"
        >
          ×
        </button>

        <div className="profile-content">
          <div className="profile-left">
            <div className="avatar-wrapper">
              <div className="avatar-square">
                {avatarUrl ? (
                  <img
                    src={avatarUrl}
                    alt="Avatar do usuário"
                    className="avatar-img"
                    onError={() => {
                      setAvatarUrl(null);
                      localStorage.removeItem('user_avatar');
                    }}
                  />
                ) : (
                  <div className="avatar-placeholder">
                    {userName.split(' ').map(n => n[0]).join('').toUpperCase()}
                  </div>
                )}
              </div>
              
              <p style={{ 
                textAlign: 'center', 
                marginTop: '10px', 
                fontSize: '0.85rem', 
                color: '#666' 
              }}>
                Gerencie seu avatar no menu do perfil acima
              </p>
            </div>
          </div>

          <div className="profile-right">
            <div className="profile-name-row">
              {isEditingName ? (
                <div className="name-edit-wrapper">
                  <input
                    className="profile-name-input"
                    value={userName}
                    onChange={(e) => setUserName(e.target.value)}
                    onBlur={handleNameSave}
                    onKeyDown={handleNameKeyDown}
                    autoFocus
                    maxLength={50}
                  />
                  <div className="name-edit-hint">
                    Pressione Enter para salvar, ESC para cancelar
                  </div>
                </div>
              ) : (
                <h2 className="profile-username">
                  {userName}
                </h2>
              )}

              <button
                className="profile-edit-inline"
                onClick={() => setIsEditingName(!isEditingName)}
                type="button"
                aria-label={isEditingName ? 'Cancelar edição' : 'Editar nome'}
              >
                {isEditingName ? 'Cancelar' : 'Editar'}
              </button>
            </div>

            {error && (
              <div className="error-message">
                {error}
              </div>
            )}

            <div className="profile-info">
              <p className="profile-email">
                <span>Email:</span>
                <strong>{userEmail}</strong>
              </p>

              <p className="profile-role">
                <span>Cargo:</span>
                <strong>{userRole}</strong>
              </p>
            </div>

            <div className="profile-actions">
              <button
                className="btn btn-close"
                onClick={handleClose}
              >
                Fechar Perfil
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProfilePage;