import getGreetingMessage from "../../utils/greetingHandler";
import { clearAllCache } from "../../slices/apiDataManager";
import AuthRepository from "../../repositories/AuthRepository";
import {useDispatch, } from "react-redux";
import {changeMaster} from "../../slices/localVariablesSlice";
import useMaster from "../../hooks/masterHook/useMaster";
import {useProfile} from "../../hooks/useProfile";
import {useNavigate} from "react-router-dom";

const Header = () =>
{
  const {profile} = useProfile()
  const dispatch = useDispatch( changeMaster( "Job Role" ) )
  const {data, loading} = useMaster()
  const navigate = useNavigate()
  const getRole = (roles,joRoleId) =>
  {
    if (!Array.isArray(roles)) return "User"; 
    let role = roles.find( role => role.id === joRoleId )
    return role ? role.name : "User";
  }
  const handleLogout = (e) => {
    e.preventDefault(); // Prevent default anchor behavior (e.g., page reload)
    logout();
  };

  const logout = async () => {
    try {
      // Notify server about the logout (optional)
      let data = {
        refreshToken: localStorage.getItem("refreshToken"),
      };

      AuthRepository.logout(data)
        .then((response) => {
          localStorage.removeItem("jwtToken");
          localStorage.removeItem("refreshToken");
          localStorage.removeItem("user");
          localStorage.clear();
          clearAllCache();
          window.location.href = "/auth/login";
        })
        .catch((error) => {
          localStorage.removeItem("jwtToken");
          localStorage.removeItem("refreshToken");
          localStorage.removeItem("user");
          clearAllCache();
          window.location.href = "/auth/login";
        });

    } catch (error) {
      console.error(
        "Error during logout:",
        error.response?.data || error.message
      );
    }
  };


  const handleProfilePage = ()=>{
   navigate(`/employee/${profile?.employeeInfo?.id}?for=account`)
  }
  return (
    <nav
      className="layout-navbar container-xxl navbar navbar-expand-xl navbar-detached align-items-center bg-navbar-theme"
      id="layout-navbar"
    >
      <div className="layout-menu-toggle navbar-nav align-items-xl-center me-3 me-xl-0 d-xl-none">
        <a
          aria-label="toggle for sidebar"
          className="nav-item nav-link px-0 me-xl-4"
          href="#"
        >
          <i className="bx bx-menu bx-sm"></i>
        </a>
      </div>
      <div
        className="navbar-nav-right d-flex align-items-center"
        id="navbar-collapse"
      >
        <marquee> {getGreetingMessage(profile?.employeeInfo?.firstName)}</marquee>
        <ul className="navbar-nav flex-row align-items-center ms-auto">
          <li className="nav-item navbar-dropdown dropdown-user dropdown">
            <a
              aria-label="dropdown profile avatar"
              className="nav-link dropdown-toggle hide-arrow"
              href="#"
              data-bs-toggle="dropdown"
            >
              <div className="avatar avatar-online">
                <img
                  src="../assets/img/avatars/00.jpg"
                  className="w-px-40 h-auto rounded-circle"
                  alt="avatar-image"
                  aria-label="Avatar Image"
                />
              </div>
            </a>
            <ul className="dropdown-menu dropdown-menu-end">
              <li onClick={handleProfilePage}>
                <a
                  aria-label="go to profile"
                  className="dropdown-item"
                  
                >
                  <div className="d-flex">
                    <div className="flex-shrink-0 me-3">
                      <div className="avatar avatar-online">
                        <img
                          src="../assets/img/avatars/00.jpg"
                          className="w-px-40 h-auto rounded-circle"
                          alt="avatar-image"
                          aria-label="Avatar Image"
                        />
                      </div>
                    </div>
                    <div className="flex-grow-1">
                      <span className="fw-medium d-block">{profile?.employeeInfo?.firstName}</span>
                      <small className="text-muted">{ getRole(data,profile?.employeeInfo?.joRoleId)}</small>
                    </div>
                  </div>
                </a>
              </li>
              <li>
                <div className="dropdown-divider"></div>
              </li>
              <li onClick={handleProfilePage} >
                <a
                  aria-label="go to profile"
                  className="dropdown-item cusor-pointer"
                  
                >
                  <i className="bx bx-user me-2"></i>
                  <span className="align-middle">My Profile</span>
                </a>
              </li>
              <li>
                <a
                  aria-label="go to setting"
                  className="dropdown-item"
               
                >
                  <i className="bx bx-cog me-2"></i>
                  <span className="align-middle">Settings</span>
                </a>
              </li>
              <li>
                <a
                  aria-label="go to billing"
                  className="dropdown-item"
              
                >
                  <span className="d-flex align-items-center align-middle">
                    <i className="flex-shrink-0 bx bx-credit-card me-2"></i>
                    <span className="flex-grow-1 align-middle ms-1">
                      Billing
                    </span>
                    <span className="flex-shrink-0 badge badge-center rounded-pill bg-danger w-px-20 h-px-20">
                      4
                    </span>
                  </span>
                </a>
              </li>
              <li>
                <div className="dropdown-divider"></div>
              </li>
              <li>
                <a
                  aria-label="click to log out"
                  className="dropdown-item"
                  href="/logout" // Optional: Add this for accessibility, but it won't actually redirect
                  onClick={handleLogout}
                >
                  <i className="bx bx-power-off me-2"></i>
                  <span className="align-middle">Log Out</span>
                </a>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </nav>
  );
};
export default Header;
