import getGreetingMessage from "../../utils/greetingHandler";
import { clearAllCache } from "../../slices/apiDataManager";
import AuthRepository from "../../repositories/AuthRepository";
import { useDispatch, useSelector } from "react-redux";
import { changeMaster, setProjectId } from "../../slices/localVariablesSlice";
import useMaster from "../../hooks/masterHook/useMaster";
import { useProfile } from "../../hooks/useProfile";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import Avatar from "../../components/common/Avatar";
import { useChangePassword } from "../Context/ChangePasswordContext";
import { useProjects } from "../../hooks/useProjects";
import { useEffect, useState } from "react";
import { useProjectName } from "../../hooks/useProjects";

const Header = () => {
  const { profile } = useProfile();
  const location = useLocation();
  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=attendance`);
  };
  // const { projects, loading: projectLoading } = useProjects();
  const { projectNames, loading: projectLoading } = useProjectName();

  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );

  const selectedProjectName = projectNames?.find(
    (p) => p?.id === selectedProject
  )?.name;

  let displayText = "";
  if (selectedProjectName) {
    displayText = selectedProjectName;
  } else if (projectLoading && selectedProject) {
    displayText = selectedProject;
  } else if (projectLoading) {
    displayText = "Loading...";
  }

  const { openChangePassword } = useChangePassword();
  useEffect(() => {
    if (projectNames && selectedProject !== " ") {
      dispatch(setProjectId(projectNames[0]?.id));
    }
  }, [projectNames]);

  /** Check if current page id project details page */
  const isProjectPath = /^\/projects\/[a-f0-9-]{36}$/.test(location.pathname);

  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"
        >
          <i className="bx bx-menu bx-sm"></i>
        </a>
      </div>
      <div
        className="navbar-nav-right d-flex align-items-center justify-content-between"
        id="navbar-collapse"
      >
        {projectNames?.length > 0 && (
          <div className=" align-items-center">
            {!isProjectPath && (
              <>
                <i
                  className="rounded-circle bx bx-building-house"
                  style={{ fontSize: "xx-large" }}
                ></i>
                <div className="btn-group">
                  <button
                    className={`btn btn-sm-sm btn-xl ${
                      projectNames?.length > 1 && "dropdown-toggle"
                    } px-1`}
                    type="button"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                  >
                    {displayText}
                  </button>

                  {projectNames?.length > 1 && (
                    <ul
                      className="dropdown-menu"
                      style={{ overflow: "auto", maxHeight: "300px" }}
                    >
                      {[...projectNames]
                        .sort((a, b) => a.name.localeCompare(b.name))
                        .map((project) => (
                          <li key={project?.id}>
                            <button
                              className="dropdown-item"
                              onClick={() =>
                                dispatch(setProjectId(project?.id))
                              }
                            >
                              {project?.name}{" "}
                              {project?.shortName ? (
                                <span className="text-primary fw-semibold">
                                  {" "}
                                  ({project?.shortName})
                                </span>
                              ) : (
                                ""
                              )}
                            </button>
                          </li>
                        ))}
                    </ul>
                  )}
                </div>
              </>
            )}
          </div>
        )}

        <ul className="navbar-nav flex-row align-items-center ms-md-auto">
          <li className="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0">
            <a
              className="nav-link dropdown-toggle hide-arrow"

              data-bs-toggle="dropdown"
              data-bs-auto-close="true"
              aria-expanded="false"
            >
              <i className="icon-base bx bx-grid-alt icon-md"></i>
            </a>
            <div className="dropdown-menu dropdown-menu-end p-0">
              <div className="dropdown-menu-header border-bottom">
                <div className="dropdown-header d-flex align-items-center py-3">
                  <h6 className="mb-0 me-auto">Shortcuts</h6>
                  <a
                    className="dropdown-shortcuts-add py-2 cusror-pointer"
                    data-bs-toggle="tooltip"
                    data-bs-placement="top"
                    aria-label="Add shortcuts"
                    data-bs-original-title="Add shortcuts"
                  >
                    <i className="icon-base bx bx-plus-circle text-heading"></i>
                  </a>
                </div>
              </div>
              <div className="dropdown-shortcuts-list scrollable-container ps">
                <div className="row row-bordered overflow-visible g-0">
                  <div className="dropdown-shortcuts-item col">
                    <a
                      onClick={() => navigate(`/dashboard`)}
                      className="text-heading text-truncate cursor-pointer"
                    >
                      <span className="dropdown-shortcuts-icon rounded-circle mb-3">
                        <i className="icon-base bx bx-home icon-26px text-heading"></i>
                      </span>
                      Dashboard
                    </a>

                    <small>User Dashboard</small>
                  </div>
                  <div className="dropdown-shortcuts-item col">
                    <a
                      onClick={() => navigate(`/projectNames`)}
                      className="text-heading text-truncate cursor-pointer"
                    >
                      <span className="dropdown-shortcuts-icon rounded-circle mb-3">
                        <i className="icon-base bx bx-building-house icon-26px text-heading"></i>
                      </span>
                      Projects
                    </a>

                    <small>Projects List</small>
                  </div>
                </div>
                <div className="row row-bordered overflow-visible g-0">
                  <div className="dropdown-shortcuts-item col">
                    <a
                      onClick={() => navigate(`/employees`)}
                      className="text-heading text-truncate cursor-pointer"
                    >
                      <span className="dropdown-shortcuts-icon rounded-circle mb-3">
                        <i className="icon-base bx bxs-user-account icon-26px text-heading"></i>
                      </span>
                      Employees
                    </a>
                    <small>Manage Employees</small>
                  </div>
                  <div className="dropdown-shortcuts-item col">
                    <a
                      onClick={() => navigate(`/activities/attendance`)}
                      className="text-heading text-truncate cursor-pointer"
                    >
                      <span className="dropdown-shortcuts-icon rounded-circle mb-3">
                        <i className="icon-base bx bx-user-check icon-26px text-heading"></i>
                      </span>
                      Attendance
                    </a>
                    <small>Manage Attendance</small>
                  </div>
                </div>
                <div className="row row-bordered overflow-visible g-0">
                  <div className="dropdown-shortcuts-item col">
                    <a
                      onClick={() => navigate(`/activities/task`)}
                      className="text-heading text-truncate cursor-pointer"
                    >
                      <span className="dropdown-shortcuts-icon rounded-circle mb-3">
                        <i className="icon-base bx bxs-wrench icon-26px text-heading"></i>
                      </span>
                      Allocate Work
                    </a>

                    <small>Work Allocations</small>
                  </div>
                  <div className="dropdown-shortcuts-item col">
                    <a
                      onClick={() => navigate(`/activities/records`)}
                      className="text-heading text-truncate cursor-pointer"
                    >
                      <span className="dropdown-shortcuts-icon rounded-circle mb-3">
                        <i className="icon-base bx bx-list-ul icon-26px text-heading"></i>
                      </span>
                      Daily Work Log
                    </a>

                    <small>Daily Work Allocations</small>
                  </div>
                </div>
              </div>
            </div>
          </li>

          {/* <li className="nav-item dropdown-notifications navbar-dropdown dropdown me-2 me-xl-0">
            <a
              className="nav-link dropdown-toggle hide-arrow cursor-pointer"
              data-bs-toggle="dropdown"
              data-bs-auto-close="outside"
              aria-expanded="false"
            >
              <span className="position-relative">
                <i className="icon-base bx bx-bell icon-lg"></i>
                <span className="badge rounded-pill bg-danger badge-dot badge-notifications border"></span>
              </span>
            </a>
            <ul className="dropdown-menu dropdown-menu-end p-0">
              <li className="dropdown-menu-header border-bottom">
                <div className="dropdown-header d-flex align-items-center py-3">
                  <h6 className="mb-0 me-auto">Notification</h6>
                  <div className="d-flex align-items-center h6 mb-0">
                    <span className="badge bg-label-primary me-2">8 New</span>
                    <a
                      href="#"
                      className="dropdown-notifications-all p-2"
                      data-bs-toggle="tooltip"
                      data-bs-placement="top"
                      aria-label="Mark all as read"
                      data-bs-original-title="Mark all as read"
                    >
                      <i className="icon-base bx bx-envelope-open text-heading"></i>
                    </a>
                  </div>
                </div>
              </li>
              <li className="dropdown-notifications-list scrollable-container ps">
                <ul className="list-group list-group-flush">
                  <li className="list-group-item list-group-item-action dropdown-notifications-item">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <img
                            src="../../assets/img/avatars/1.png"
                            alt=""
                            className="rounded-circle"
                          ></img>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">Congratulation Lettie 🎉</h6>
                        <small className="mb-1 d-block text-body">
                          Won the monthly best seller gold badge
                        </small>
                        <small className="text-body-secondary">1h ago</small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <span className="avatar-initial rounded-circle bg-label-danger">
                            CF
                          </span>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">Charles Franklin</h6>
                        <small className="mb-1 d-block text-body">
                          Accepted your connection
                        </small>
                        <small className="text-body-secondary">12hr ago</small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <img
                            src="../../assets/img/avatars/2.png"
                            alt=""
                            className="rounded-circle"
                          ></img>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">New Message ✉️</h6>
                        <small className="mb-1 d-block text-body">
                          You have new message from Natalie
                        </small>
                        <small className="text-body-secondary">1h ago</small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <span className="avatar-initial rounded-circle bg-label-success">
                            <i className="icon-base bx bx-cart"></i>
                          </span>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">
                          Whoo! You have new order 🛒
                        </h6>
                        <small className="mb-1 d-block text-body">
                          ACME Inc. made new order $1,154
                        </small>
                        <small className="text-body-secondary">1 day ago</small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <img
                            src="../../assets/img/avatars/9.png"
                            alt=""
                            className="rounded-circle"
                          ></img>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">
                          Application has been approved 🚀
                        </h6>
                        <small className="mb-1 d-block text-body">
                          Your ABC project application has been approved.
                        </small>
                        <small className="text-body-secondary">
                          2 days ago
                        </small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <span className="avatar-initial rounded-circle bg-label-success">
                            <i className="icon-base bx bx-pie-chart-alt"></i>
                          </span>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">
                          Monthly report is generated
                        </h6>
                        <small className="mb-1 d-block text-body">
                          July monthly financial report is generated{" "}
                        </small>
                        <small className="text-body-secondary">
                          3 days ago
                        </small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <img
                            src="../../assets/img/avatars/5.png"
                            alt=""
                            className="rounded-circle"
                          ></img>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">Send connection request</h6>
                        <small className="mb-1 d-block text-body">
                          Peter sent you connection request
                        </small>
                        <small className="text-body-secondary">
                          4 days ago
                        </small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <img
                            src="../../assets/img/avatars/6.png"
                            alt=""
                            className="rounded-circle"
                          ></img>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">New message from Jane</h6>
                        <small className="mb-1 d-block text-body">
                          Your have new message from Jane
                        </small>
                        <small className="text-body-secondary">
                          5 days ago
                        </small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                  <li className="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                    <div className="d-flex">
                      <div className="flex-shrink-0 me-3">
                        <div className="avatar">
                          <span className="avatar-initial rounded-circle bg-label-warning">
                            <i className="icon-base bx bx-error"></i>
                          </span>
                        </div>
                      </div>
                      <div className="flex-grow-1">
                        <h6 className="small mb-0">CPU is running high</h6>
                        <small className="mb-1 d-block text-body">
                          CPU Utilization Percent is currently at 88.63%,
                        </small>
                        <small className="text-body-secondary">
                          5 days ago
                        </small>
                      </div>
                      <div className="flex-shrink-0 dropdown-notifications-actions">
                        <a href="#" className="dropdown-notifications-read">
                          <span className="badge badge-dot"></span>
                        </a>
                        <a href="#" className="dropdown-notifications-archive">
                          <span className="icon-base bx bx-x"></span>
                        </a>
                      </div>
                    </div>
                  </li>
                </ul>
  
              </li>
              <li className="border-top">
                <div className="d-grid p-4">
                  <a className="btn btn-primary btn-sm d-flex" href="#;">
                    <small className="align-middle">
                      View all notifications
                    </small>
                  </a>
                </div>
              </li>
            </ul>
          </li> */}
          <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">
                <Avatar
                  firstName={`${profile?.employeeInfo?.firstName}`}
                  lastName={`${profile?.employeeInfo?.lastName}`}
                />
              </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">
                        <Avatar
                          firstName={`${profile?.employeeInfo?.firstName}`}
                          lastName={`${profile?.employeeInfo?.lastName}`}
                        />
                      </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 onClick={handleProfilePage}>
                <a
                  aria-label="go to setting "
                  className="dropdown-item cusor-pointer"
                >
                  <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 cusor-pointer"
                >
                  <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 onClick={openChangePassword}>
                {" "}
                {/* Use the function from the context */}
                <a
                  aria-label="go to profile"
                  className="dropdown-item cusor-pointer"
                >
                  <i className="bx bx-lock-alt me-2"></i>
                  <span className="align-middle">Change Password</span>
                </a>
              </li>
              <li>
                <div className="dropdown-divider"></div>
              </li>
              <li>
                <a
                  aria-label="click to log out"
                  className="dropdown-item cusor-pointer"
                  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;
