import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/router";
import { useContext, useEffect, useState } from "react";
import { AuthContextType } from "../..";
import { AuthContext } from "../../contexts/auth";
import { menuData } from "../../data/menuData";
import { useGetProfileType } from "../../hooks/useGetProfileType";
import { useGetCompanyProfileDetails } from "../../utils/hooks";
import { useGetCandidateProfileDetails } from "../../utils/hooks/useGetCandidateProfileDetails";
import { useGetCandidateUnreadNotification } from "../../utils/hooks/useGetCandidateUnreadNotification";
import { useGetCompanyUnreadNotification } from "../../utils/hooks/useGetCompanyUnreadNotification";
import { isActiveLink } from "../../utils/linkActiveChecker";
import { LogOutAlert } from "../common/LogOutAlert";
import HeaderNavContent from "./HeaderNavContent";

interface Props {
  logo: string;
  ac_holder: string;
}

const allowedMenuOptionsForCandidate = [
  "My Profile",
  "Logout",
  "Applied Jobs",
  "Messages",
]; // Add the menu names that you want to display

const allowedMenuOptionsForCompany = [
  "Company Profile",
  "Logout",
  "Messages",
  "All Applicants",
];

const DashboardHeader = ({ logo, ac_holder }: Props) => {
  const [navbar, setNavbar] = useState(false);
  // const [getProfilePicture, setProfilePicture] = useState<string>("");
  // const [getProfileName, setProfilePicture] = useState<string>("");
  const [getProfileDetails, setProfileDetails] =
    useState<DashboardHeaderProfile>({
      picture: "",
      name: "",
    });
  const { name, userRole } = useContext(AuthContext) as AuthContextType;
  const [getNotificationsCount, setNotificationsCount] = useState<number>(0);
  const [candidateId, setCandidateId] = useState<number>(0);

  const FetchCandidateDetails = async () => {
    try {
      // setIsLoading(true);
      const profileType = useGetProfileType();

      let resp, status;
      if (profileType === "Candidate") {
        // Call Candidate profile details API
        const candidateResponse =
          (await useGetCandidateProfileDetails()) as CandidateProfileDetailsResp;
        resp = candidateResponse.resp;
        status = candidateResponse.status;
        setProfileDetails({
          name: resp.firstName!,
          picture: resp!.profilePictureUrl!,
        });
        setCandidateId(resp.id!);
      } else if (profileType === "Company") {
        // Call Company profile details API
        const companyResponse =
          (await useGetCompanyProfileDetails()) as CompanyProfileDetailsResp;
        resp = companyResponse.resp;
        status = companyResponse.status;
        setProfileDetails({
          name: resp.name!,
          picture: resp!.profilePictureUrl!,
        });
      }

      // setIsLoading(false);
    } catch (error) {
      console.error(
        "Error Occurred when fetching the candidate account details",
        error,
      );
    }
  };
  const FetNotificationCount = async () => {
    try {
      // setIsLoading(true);
      const { resp } = (await (
        userRole === "Candidate"
          ? useGetCandidateUnreadNotification
          : useGetCompanyUnreadNotification
      )()) as Response;
      // console.log("resp>>>>", resp);
      setNotificationsCount(resp.meta.total);
      // setIsLoading(false);
    } catch (error) {
      console.error(
        "Error Occurred when fetching the notification count",
        error,
      );
    }
  };

  useEffect(() => {
    FetchCandidateDetails();
    FetNotificationCount();
  }, []);

  const router = useRouter();

  const changeBackground = () => {
    if (window.scrollY >= 0) {
      setNavbar(true);
    } else {
      setNavbar(false);
    }
  };

  useEffect(() => {
    window.addEventListener("scroll", changeBackground);
  }, []);

  const filteredMenuData = menuData.filter((item) => {
    const profileType = useGetProfileType();
    if (profileType === "Candidate") {
      return allowedMenuOptionsForCandidate.includes(item.name);
    } else if (profileType === "Company") {
      return allowedMenuOptionsForCompany.includes(item.name);
    }
  });
  const handleLogout = async () => {
    const confirmed = await LogOutAlert(); // Wait for confirmation
    if (confirmed) {
      router.push("/logout"); // Perform routing after successful logout
    }
  };

  return (
    <header
      className={`main-header header-shaddow ${navbar ? "fixed-header" : ""}`}
    >
      <div className="container-fluid">
        <div className="main-box">
          <div className="nav-outer">
            <div className="logo-box">
              <div className="logo">
                <Link href="/">
                  <img
                    alt="brand"
                    src="/images/human_capital_logo.png"
                    width={154}
                    height={50}
                  />
                </Link>
              </div>
            </div>

            <HeaderNavContent />
          </div>

          <div className="outer-box">
            {/* <button className="menu-btn">
              <span className="count">1</span>
              <span className="icon la la-heart-o"></span>
            </button> */}

            {userRole == "Candidate" && (
              <Link
                href="/dashboard/cv-manager"
                id="upload_cv"
                className="upload-cv"
              >
                Create your CV
              </Link>
            )}

            <Link href={"/dashboard/notifications"} className="menu-btn">
              {/* <span className="count ">10+</span> */}
              {getNotificationsCount > 0 && (
                <span className="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                  {getNotificationsCount > 99 ? "99+" : getNotificationsCount}
                  <span className="visually-hidden">unread notifications</span>
                </span>
              )}
              <span className="icon la la-bell-o"></span>
            </Link>

            <div className="dropdown dashboard-option">
              <a
                className="dropdown-toggle"
                role="button"
                data-bs-toggle="dropdown"
                aria-expanded="false"
              >
                <img
                  alt="avatar"
                  className="thumb"
                  src={
                    getProfileDetails.picture
                      ? getProfileDetails.picture
                      : "/images/human_capital_logo.png"
                  }
                  width={50}
                  height={50}
                  onError={(e: any) => {
                    e.target.src = "/images/human_capital_logo.png";
                    e.target.onerror = null;
                  }}
                />
                <span className="name">
                  {getProfileDetails.name.split(" ")[0]}
                </span>
              </a>

              <ul className="dropdown-menu">
                {filteredMenuData.map((item) => {
                  // Handle Exams submenu
                  if (item.submenu) {
                    return (
                      <li key={item.id}>
                        <details className="group cursor-pointer">
                          <summary className="flex items-center justify-between px-3 py-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700">
                            <span>
                              <i className={`la ${item.icon}`}></i> {item.name}
                            </span>
                            <svg
                              className="fill-white transition group-open:rotate-180"
                              width="16"
                              height="16"
                              viewBox="0 0 20 20"
                              fill="white"
                              xmlns="http://www.w3.org/2000/svg"
                            >
                              <path
                                fillRule="evenodd"
                                clipRule="evenodd"
                                d="M4.41107 6.9107C4.73651 6.58527 5.26414 6.58527 5.58958 6.9107L10.0003 11.3214L14.4111 6.91071C14.7365 6.58527 15.2641 6.58527 15.5896 6.91071C15.915 7.23614 15.915 7.76378 15.5896 8.08922L10.5896 13.0892C10.2641 13.4147 9.73651 13.4147 9.41107 13.0892L4.41107 8.08922C4.08563 7.76378 4.08563 7.23614 4.41107 6.9107Z"
                                fill="white"
                              />
                            </svg>
                          </summary>
                          <div className="pl-4 mt-1 flex flex-col gap-1">
                            {item.submenu.map((subitem, index) => (
                              <Link
                                key={index}
                                href={subitem.routePath}
                                className={`block px-3 py-2 text-sm rounded hover:bg-gray-200 dark:hover:bg-gray-700 ${
                                  isActiveLink(subitem.routePath, router.asPath)
                                    ? "font-semibold text-primary"
                                    : ""
                                }`}
                              >
                                {subitem.name}
                              </Link>
                            ))}
                          </div>
                        </details>
                      </li>
                    );
                  }

                  // Regular menu items
                  return (
                    <li
                      className={`${
                        isActiveLink(item.routePath, router.asPath)
                          ? "active"
                          : ""
                      } mb-1`}
                      key={item.id}
                    >
                      {item.name === "Logout" ? (
                        <Link href="#" onClick={handleLogout}>
                          <i className={`la ${item.icon}`}></i> {item.name}
                        </Link>
                      ) : item.name === "My Profile" ? (
                        <Link href={`/candidate/${candidateId}`}>
                          <i className={`la ${item.icon}`}></i> {item.name}
                        </Link>
                      ) : (
                        <Link href={item.routePath}>
                          <i className={`la ${item.icon}`}></i> {item.name}
                        </Link>
                      )}
                    </li>
                  );
                })}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </header>
  );
};

export default DashboardHeader;
