import {
  useState
} from "react";

import {
  NavLink,
  Outlet,
  useLocation,
  useNavigate
} from "react-router-dom";

import {
  useAdminAuth
} from "../context/AdminAuthContext";

/* =========================================================
   ROLE LABELS
   ========================================================= */

const roleLabels = {
  super_admin:
    "Super Administrator",

  hr_admin:
    "HR Administrator",

  hr_reviewer:
    "HR Reviewer",

  viewer:
    "Read-only User"
};

/* =========================================================
   NAVIGATION
   ========================================================= */

const navigationItems = [
  {
    path:
      "/admin/dashboard",

    label:
      "Dashboard",

    shortLabel:
      "DB"
  },

  {
    path:
      "/admin/submissions",

    label:
      "Staff Submissions",

    shortLabel:
      "SS"
  },

  {
    path:
      "/admin/review",

    label:
      "Staff Record Review",

    shortLabel:
      "RV"
  },

  {
    path:
      "/admin/reviewers",

    label:
      "Review Assignments",

    shortLabel:
      "RA",

    roles: [
      "super_admin",
      "hr_admin"
    ]
  },

  {
    path:
      "/admin/audit-log",

    label:
      "Audit Log",

    shortLabel:
      "AL",

    roles: [
      "super_admin",
      "hr_admin"
    ]
  },

  {
    path:
      "/admin/users",

    label:
      "Admin Users",

    shortLabel:
      "AU",

    roles: [
      "super_admin"
    ]
  }
];

/* =========================================================
   PAGE TITLE
   ========================================================= */

const getPageTitle = (
  pathname
) => {
  if (
    pathname.match(
      /^\/admin\/submissions\/[^/]+$/
    )
  ) {
    return "Submission Review";
  }

  if (
    pathname.startsWith(
      "/admin/submissions"
    )
  ) {
    return "Staff Submissions";
  }

  if (
    pathname.startsWith(
      "/admin/reviewers"
    )
  ) {
    return "Review Assignments";
  }

  if (
    pathname.startsWith(
      "/admin/review"
    )
  ) {
    return "Staff Record Review";
  }

  if (
    pathname.startsWith(
      "/admin/audit-log"
    )
  ) {
    return "Audit Log";
  }

  if (
    pathname.startsWith(
      "/admin/users"
    )
  ) {
    return "Administrator Users";
  }

  return "Dashboard";
};

/* =========================================================
   COMPONENT
   ========================================================= */

const AdminLayout = () => {
  const navigate =
    useNavigate();

  const location =
    useLocation();

  const {
    admin,
    logout
  } = useAdminAuth();

  const [
    sidebarOpen,
    setSidebarOpen
  ] = useState(false);

  const [
    loggingOut,
    setLoggingOut
  ] = useState(false);

  const [
    logoutError,
    setLogoutError
  ] = useState("");

  const adminRole =
    admin?.role || "";

  const adminName =
    admin?.full_name ||
    admin?.name ||
    "Administrator";

  const adminEmail =
    admin?.email || "";

  const visibleNavigation =
    navigationItems.filter(
      (
        navigationItem
      ) => {
        if (
          !navigationItem.roles
        ) {
          return true;
        }

        return navigationItem
          .roles
          .includes(
            adminRole
          );
      }
    );

  /* =========================================================
     LOGOUT
     ========================================================= */

  const handleLogout =
    async () => {
      if (loggingOut) {
        return;
      }

      try {
        setLoggingOut(true);
        setLogoutError("");

        await logout();

        navigate(
          "/admin/login",
          {
            replace: true
          }
        );
      } catch (
        error
      ) {
        console.error(
          "Administrator logout error:",
          error
        );

        setLogoutError(
          error.response?.data
            ?.message ||
            error.message ||
            "Unable to sign out. Please try again."
        );
      } finally {
        setLoggingOut(false);
      }
    };

  /* =========================================================
     RENDER
     ========================================================= */

  return (
    <div className="admin-shell">
      {/* Mobile sidebar overlay */}

      {sidebarOpen && (
        <button
          type="button"
          className="admin-sidebar-overlay"
          aria-label="Close navigation"
          onClick={() =>
            setSidebarOpen(
              false
            )
          }
        />
      )}

      {/* =====================================================
          SIDEBAR
          ===================================================== */}

      <aside
        className={[
          "admin-sidebar",

          sidebarOpen
            ? "admin-sidebar--open"
            : ""
        ]
          .filter(Boolean)
          .join(" ")}
      >
        <div className="admin-sidebar__brand">
          <div className="admin-brand-mark">
            C
          </div>

          <div>
            <strong>
              CAGD SRMS
            </strong>

            <span>
              Administration
            </span>
          </div>
        </div>

        <nav
          className="admin-navigation"
          aria-label="Administrator navigation"
        >
          <span className="admin-navigation__label">
            Main menu
          </span>

          {visibleNavigation.map(
            (
              navigationItem
            ) => (
              <NavLink
                key={
                  navigationItem.path
                }
                to={
                  navigationItem.path
                }
                className={({
                  isActive
                }) =>
                  [
                    "admin-nav-link",

                    isActive
                      ? "admin-nav-link--active"
                      : ""
                  ]
                    .filter(Boolean)
                    .join(" ")
                }
                onClick={() =>
                  setSidebarOpen(
                    false
                  )
                }
              >
                <span className="admin-nav-link__icon">
                  {
                    navigationItem
                      .shortLabel
                  }
                </span>

                <span>
                  {
                    navigationItem
                      .label
                  }
                </span>
              </NavLink>
            )
          )}
        </nav>

        <div className="admin-sidebar__account">
          <div className="admin-account-avatar">
            {adminName
              .charAt(0)
              .toUpperCase()}
          </div>

          <div className="admin-account-details">
            <strong>
              {adminName}
            </strong>

            <span>
              {roleLabels[
                adminRole
              ] ||
                adminRole ||
                "Administrator"}
            </span>
          </div>
        </div>
      </aside>

      {/* =====================================================
          MAIN AREA
          ===================================================== */}

      <div className="admin-main">
        <header className="admin-topbar">
          <div className="admin-topbar__left">
            <button
              type="button"
              className="admin-menu-button"
              onClick={() =>
                setSidebarOpen(
                  (
                    currentValue
                  ) =>
                    !currentValue
                )
              }
              aria-label={
                sidebarOpen
                  ? "Close navigation"
                  : "Open navigation"
              }
              aria-expanded={
                sidebarOpen
              }
            >
              ☰
            </button>

            <div>
              <span>
                Human Resource Portal
              </span>

              <h1>
                {getPageTitle(
                  location.pathname
                )}
              </h1>
            </div>
          </div>

          <div className="admin-topbar__right">
            <div className="admin-topbar-user">
              <strong>
                {adminName}
              </strong>

              {adminEmail && (
                <span>
                  {adminEmail}
                </span>
              )}
            </div>

            <button
              type="button"
              className="admin-logout-button"
              onClick={
                handleLogout
              }
              disabled={
                loggingOut
              }
            >
              {loggingOut
                ? "Signing out..."
                : "Sign out"}
            </button>
          </div>
        </header>

        <main className="admin-content">
          {logoutError && (
            <div
              className="form-alert form-alert--error"
              role="alert"
            >
              {logoutError}
            </div>
          )}

          <Outlet />
        </main>
      </div>
    </div>
  );
};

export default AdminLayout;