import Link from "next/link";
import { CircularProgressbar, buildStyles } from "react-circular-progressbar";
import "react-circular-progressbar/dist/styles.css";
import { isActiveLink } from "../../utils/linkActiveChecker";
import { useRouter } from "next/router";
import { menuData } from "../../data/menuData";
import { AuthContextType } from "../..";
import { useContext, useEffect, useState } from "react";
import { AuthContext } from "../../contexts/auth";
import { LogOutAlert } from "../common/LogOutAlert";
import { useGetCandidateProfileDetails } from "../../utils/hooks/useGetCandidateProfileDetails";

interface Props {
  getIsSidebarOpen: boolean;
  setIsSidebarOpen: React.Dispatch<React.SetStateAction<boolean>>;
}

const allowedMenuOptionsForCandidate = [
  "Dashboard",
  "My Profile",
  "Scheduled Interview",
  "Applied Jobs",
  "Job Alerts",
  "Saved Jobs",
  // "Shortlisted Jobs",
  "CV manager",
  // "Packages",
  "Messages",
  "Subscriptions",
  "Change Password",
  "Exams",
  "Logout",
  "Change Password",
];

const allowedMenuOptionsForCompany = [
  "Company Dashboard",
  "Company Profile",
  "Post a New Job",
  "Manage Jobs",
  "All Applicants",
  "Shortlisted CVs",
  // "Resume Alerts",
  "Skill Test",
  // "Company Packages",
  "Messages",
  "Subscriptions",
  "Change Password",
  "Logout",
  "Change Password",
  "Scheduled Interviews",
];

const DashboardSidebar = (props: Props) => {
  const percentage = 60;
  const router = useRouter();
  const { logout, userRole } = useContext(AuthContext) as AuthContextType;

  const handleLogout = async () => {
    const confirmed = await LogOutAlert(); // Wait for confirmation
    if (confirmed) {
      router.push("/logout"); // Perform routing after successful logout
    }
  };

  const filteredMenuDataForCandidates = menuData.filter((item) =>
    allowedMenuOptionsForCandidate.includes(item.name)
  );

  const filteredMenuDataForCompany = menuData.filter((item) =>
    allowedMenuOptionsForCompany.includes(item.name)
  );

  const [candidateId, setCandidateId] = useState<number>(0);

  const fetchCandidateProfileDetails = async () => {
    try {
      const { resp, status } =
        (await useGetCandidateProfileDetails()) as CandidateProfileDetailsResp;
      console.log("Candidate API Data", resp, status);
      setCandidateId(resp.id!);
    } catch (error) {
      console.log(
        "Error Occured when fetching the candidate account details",
        error
      );
    }
  };

  useEffect(() => {
    fetchCandidateProfileDetails();
  }, []);

  return (
    <div
      className={`user-sidebar ${props.getIsSidebarOpen ? "sidebar_open" : ""}`}
    >
      {/* Start sidebar close icon */}
      <div className="pro-header text-end pb-0 mb-0 show-1023">
        <div
          className="fix-icon"
          onClick={() => props.setIsSidebarOpen(!props.getIsSidebarOpen)}
        >
          <span className="flaticon-close"></span>
        </div>
      </div>
      {/* End sidebar close icon */}

      <div className="sidebar-inner">
        <ul className="navigation">
          {userRole === "Candidate" &&
            filteredMenuDataForCandidates.map((item) => {
              // Handle Exams submenu
              if (item.submenu) {
                const isSubmenuActive = item.submenu.some((sub) =>
                  isActiveLink(sub.routePath, router.asPath)
                );

                return (
                  <li
                    key={item.id}
                    className={`${isSubmenuActive ? "active" : ""} mb-1`}
                  >
                    <details className="group" open={isSubmenuActive}>
                      <summary
                        className={`cursor-pointer select-none font-medium duration-300 ease-in-out hover:bg-[#3FE0D0]`}
                        style={{
                          listStyle: "none",
                          color: "white",
                          display: "flex",
                          alignItems: "center",
                          padding: "9px 30px 9px 30px",
                          backgroundColor: "transparent",
                          borderRadius: "8px",
                        }}
                      >
                        <i
                          className={`la ${item.icon}`}
                          style={{
                            fontSize: "20px",
                            marginRight: "15px",
                            color: "white",
                            width: "20px",
                            textAlign: "center",
                          }}
                        ></i>
                        <span
                          style={{
                            color: "white",
                            flex: 1,
                            marginRight: "-15px",
                          }}
                        >
                          {item.name}
                        </span>
                        <svg
                          className="fill-white transition group-open:rotate-180"
                          width="18"
                          height="18"
                          viewBox="0 0 20 20"
                          fill="white"
                          xmlns="http://www.w3.org/2000/svg"
                          style={{ flexShrink: 0 }}
                        >
                          <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="mt-2 mb-2.5 flex flex-col gap-2"
                        style={{ paddingLeft: "47px" }}
                      >
                        {item.submenu.map((subitem, index) => {
                          const isSubitemActive = isActiveLink(
                            subitem.routePath,
                            router.asPath
                          );

                          return (
                            <Link
                              key={index}
                              href={subitem.routePath}
                              className="group relative flex items-center gap-2.5 rounded-md px-4 py-2 font-medium duration-300 ease-in-out"
                              style={{
                                color: "white",
                                backgroundColor: isSubitemActive
                                  ? "#3FE0D0"
                                  : "transparent",
                                borderRadius: "8px",
                              }}
                            >
                              {subitem.name}
                            </Link>
                          );
                        })}
                      </div>
                    </details>
                  </li>
                );
              }

              if (item.name === "My Profile") {
                return (
                  <li
                    className={`${
                      isActiveLink(`/candidate/${candidateId}`, router.asPath)
                        ? "active"
                        : ""
                    } mb-1`}
                    key={item.id}
                  >
                    <Link href={`/candidate/${candidateId}`}>
                      <i className={`la ${item.icon}`}></i> {item.name}
                    </Link>
                  </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>
                  ) : (
                    <Link href={item.routePath}>
                      <i className={`la ${item.icon}`}></i> {item.name}
                    </Link>
                  )}
                </li>
              );
            })}
          {userRole === "Company" &&
            filteredMenuDataForCompany.map((item) => {
              // Handle submenus
              if (item.submenu) {
                const isSubmenuActive = item.submenu.some((sub) =>
                  isActiveLink(sub.routePath, router.asPath)
                );

                return (
                  <li
                    key={item.id}
                    className={`${isSubmenuActive ? "active" : ""} mb-1`}
                  >
                    <details className="group" open={isSubmenuActive}>
                      <summary
                        className={`cursor-pointer select-none font-medium duration-300 ease-in-out hover:bg-[#3FE0D0]`}
                        style={{
                          listStyle: "none",
                          color: "white",
                          display: "flex",
                          alignItems: "center",
                          padding: "9px 30px 9px 30px",
                          backgroundColor: "transparent",
                          borderRadius: "8px",
                        }}
                      >
                        <i
                          className={`la ${item.icon}`}
                          style={{
                            fontSize: "20px",
                            marginRight: "15px",
                            color: "white",
                            width: "20px",
                            textAlign: "center",
                          }}
                        ></i>
                        <span
                          style={{
                            color: "white",
                            flex: 1,
                            marginRight: "-15px",
                          }}
                        >
                          {item.name}
                        </span>
                        <svg
                          className="fill-white transition group-open:rotate-180"
                          width="18"
                          height="18"
                          viewBox="0 0 20 20"
                          fill="white"
                          xmlns="http://www.w3.org/2000/svg"
                          style={{ flexShrink: 0 }}
                        >
                          <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="mt-2 mb-2.5 flex flex-col gap-2"
                        style={{ paddingLeft: "47px" }}
                      >
                        {item.submenu.map((subitem, index) => {
                          const isSubitemActive = isActiveLink(
                            subitem.routePath,
                            router.asPath
                          );

                          return (
                            <Link
                              key={index}
                              href={subitem.routePath}
                              className="group relative flex items-center gap-2.5 rounded-md px-4 py-2 font-medium duration-300 ease-in-out"
                              style={{
                                color: "white",
                                backgroundColor: isSubitemActive
                                  ? "#3FE0D0"
                                  : "transparent",
                                borderRadius: "8px",
                              }}
                            >
                              {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="/logout">
                      <i className={`la ${item.icon}`}></i> {item.name}
                    </Link>
                  ) : (
                    <Link href={item.routePath}>
                      <i className={`la ${item.icon}`}></i> {item.name}
                    </Link>
                  )}
                </li>
              );
            })}
        </ul>
        {/* End navigation */}

        {userRole === "Candidate" && (
          <div className="skills-percentage">
            <h4 className="text-white">Skills Percentage</h4>
            <p className="text-white">
              `Put value for <strong>Cover Image</strong> field to increase your
              skill up to <strong>85%</strong>`
            </p>
            <div style={{ width: 200, height: 200, margin: "auto" }}>
              <CircularProgressbar
                background
                backgroundPadding={6}
                styles={buildStyles({
                  backgroundColor: "#3bcbbcff",
                  textColor: "#000203ff",
                  pathColor: "#055875",
                  trailColor: "transparent",
                })}
                value={percentage}
                text={`${percentage}%`}
              />
            </div>{" "}
            {/* <!-- Pie Graph --> */}
          </div>
        )}
      </div>
    </div>
  );
};

export default DashboardSidebar;
