import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Menu, PanelLeftOpen, PanelLeftClose } from "lucide-react";
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { AuthContext } from "Src/authContext";
import ClickOutside from "../components/ClickOutside";
import { GlobalContext } from "../globalContext";

const TopHeader = () => {
  const navigate = useNavigate();
  const { state: authState, dispatch: authDispatch } =
    React.useContext(AuthContext);
  const { state, dispatch: globalDispatch } = React.useContext(GlobalContext);
  const location = useLocation();

  let { isOpen, showProfile } = state;
  let toggleOpen = (open) =>
    globalDispatch({
      type: "OPEN_SIDEBAR",
      payload: { isOpen: open },
    });

  const handleLogout = () => {
    localStorage.removeItem("token");
    globalDispatch({
      type: "TOGGLE_PROFILE",
      payload: { showProfile: false },
    });
    authDispatch({
      type: "LOGOUT",
    });
    navigate(`${authState?.role}/login`);
  };

  let toggleProfile = (show) =>
    globalDispatch({
      type: "TOGGLE_PROFILE",
      payload: { showProfile: show },
    });

  const subscriptionType = localStorage.getItem("UserSubscription");

  return (
    <header className="z-999 sticky top-0 flex w-full bg-boxdark drop-shadow-none">
      <div className="flex flex-grow items-center justify-between px-4 py-4 shadow-2 md:px-6 2xl:px-11">
        {/* Hamburger Toggle Button */}
        <div className="flex items-center gap-2 sm:gap-4">
          {isOpen ? (
            <PanelLeftClose
              onClick={() => toggleOpen(!isOpen)}
              className="hidden h-5 w-5 cursor-pointer text-bodydark lg:block"
            />
          ) : (
            <PanelLeftOpen
              onClick={() => toggleOpen(!isOpen)}
              className="hidden h-5 w-5 cursor-pointer lg:block"
            />
          )}
          {!isOpen ? (
            <button
              className={`z-99999 block rounded border border-stroke bg-boxdark p-1.5 shadow-sm lg:hidden dark:border-strokedark`}
              onClick={() => toggleOpen(!isOpen)}
            >
              <Menu />
            </button>
          ) : null}
        </div>

        {/* Right Side Content */}
        <div className="flex items-center gap-3 2xl:gap-7">
          {/* Create Project Button */}
          {authState.role !== "client" && (
            <>
              <button
                className="rounded-lg border border-primary bg-primary px-6 py-2 text-base font-medium text-white hover:bg-opacity-90"
                onClick={() => navigate(`/${authState.role}/add-project`)}
              >
                Create New Project
              </button>
              {/* Subscription Button for Members */}
              {authState.role === "member" && (
                <button
                  className="rounded-lg border border-primary bg-transparent px-6 py-2 text-base font-medium text-white hover:bg-primary/30"
                  onClick={() => navigate(`/${authState.role}/subscription`)}
                >
                  {!subscriptionType ? "Subscribe Now" : "Upgrade Plan"}
                </button>
              )}
            </>
          )}

          {/* User Profile Dropdown */}
          <ClickOutside
            onClick={() => toggleProfile(false)}
            className="relative"
          >
            <button
              onClick={() => toggleProfile(!showProfile)}
              className="flex items-center gap-4"
            >
              <span className="hidden text-right lg:block">
                <span className="block text-sm font-medium text-white">
                  {authState.userName ?? "User"}
                </span>
                <span className="block text-xs text-gray-300">
                  {authState.companyName ?? "Company"}
                </span>
              </span>

              {authState.photo ? (
                <span className="h-12 w-12 rounded-full">
                  <img
                    crossOrigin="anonymous"
                    className="h-full w-full rounded-full object-cover"
                    src={authState.photo}
                    alt="User"
                  />
                </span>
              ) : (
                <FontAwesomeIcon
                  className="h-12 w-12 rounded-full text-gray-300"
                  icon="fa-solid fa-circle-user"
                />
              )}

              <svg
                className={`hidden fill-current sm:block ${
                  showProfile ? "rotate-180" : ""
                }`}
                width="12"
                height="8"
                viewBox="0 0 12 8"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  fillRule="evenodd"
                  clipRule="evenodd"
                  d="M0.410765 0.910734C0.736202 0.585297 1.26384 0.585297 1.58928 0.910734L6.00002 5.32148L10.4108 0.910734C10.7362 0.585297 11.2638 0.585297 11.5893 0.910734C11.9147 1.23617 11.9147 1.76381 11.5893 2.08924L6.58928 7.08924C6.26384 7.41468 5.7362 7.41468 5.41077 7.08924L0.410765 2.08924C0.0853277 1.76381 0.0853277 1.23617 0.410765 0.910734Z"
                  fill=""
                />
              </svg>
            </button>

            {/* Dropdown Menu */}
            {showProfile && (
              <div className="w-62.5 shadow-default absolute right-0 mt-4 flex flex-col rounded border border-strokedark bg-boxdark pt-4 dark:border-strokedark dark:bg-boxdark">
                <ul className="py-7.5 flex flex-col gap-5 border-b border-strokedark px-6 dark:border-strokedark">
                  <li>
                    <a
                      href={`/${authState.role}/profile`}
                      className="flex items-center gap-3.5 text-sm font-medium duration-300 ease-in-out hover:text-primary lg:text-base"
                    >
                      <FontAwesomeIcon icon="fa-solid fa-user" />
                      My Profile
                    </a>
                  </li>
                  {authState.role !== "client" ||
                  authState.role !== "manager" ? (
                    <li>
                      <a
                        href={`/${authState.role}/setting`}
                        className="flex items-center gap-3.5 whitespace-nowrap text-sm font-medium duration-300 ease-in-out hover:text-primary lg:text-base"
                      >
                        <FontAwesomeIcon icon="fa-solid fa-gear" />
                        Account Settings
                      </a>
                    </li>
                  ) : null}
                </ul>
                <button
                  onClick={handleLogout}
                  className="flex items-center gap-3.5 px-6 py-4 text-sm font-medium duration-300 ease-in-out hover:text-primary lg:text-base"
                >
                  <FontAwesomeIcon icon="fa-solid fa-right-from-bracket" />
                  Log Out
                </button>
              </div>
            )}
          </ClickOutside>
        </div>
      </div>
    </header>
  );
};

export default TopHeader;
