"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { ReactNode, Suspense, useEffect, useState } from "react";
import { BottomNav } from "@/components/app/BottomNav";
import { NotificationBell } from "@/components/app/NotificationBell";
import { HeaderUserMenu } from "@/components/app/HeaderUserMenu";
import { BrandingStyles } from "@/components/app/BrandingStyles";
import { ImpersonationBanner } from "@/components/app/ImpersonationBanner";
import { SidebarNav } from "@/components/app/SidebarNav";
import { Breadcrumb } from "@/components/layout/Breadcrumb";
import { PageBackButton } from "@/components/layout/PageBackButton";
import { useBranding } from "@/components/app/BrandingProvider";
import {
  resolveBreadcrumbs,
  resolveParentHref,
  type BreadcrumbLabels,
} from "@/lib/breadcrumbs";
import { isImpersonating, isSessionReady, getActiveRole, getActiveRoleLabel } from "@/lib/session-context";
import { getStoredUser } from "@/lib/api";
import { brandingLogoUrl } from "@/lib/branding";
import { isTeacherRole } from "@/lib/permissions";
import { roleLabels } from "@/lib/role-labels";

export function AppShell({
  children,
  title,
  subtitle,
  showBack = true,
  layout = "default",
  breadcrumbLabels,
}: {
  children: ReactNode;
  title?: string;
  subtitle?: string;
  showBack?: boolean;
  layout?: "default" | "teacher";
  breadcrumbLabels?: BreadcrumbLabels;
}) {
  const branding = useBranding();
  const logoSrc = brandingLogoUrl(branding.logo_url);
  const pathname = usePathname();
  const isHome = pathname === "/dashboard";
  const activeRole = getActiveRole();
  const roleLabel = getActiveRoleLabel() ?? (activeRole ? roleLabels[activeRole] : null) ?? "کاربر";
  const isTeacherView = isTeacherRole(activeRole);
  const isTeacherWorkspace = layout === "teacher";
  const hideSidebar = isTeacherView || isTeacherWorkspace;

  return (
    <div
      className={`min-h-screen pb-[calc(4.5rem+env(safe-area-inset-bottom))] lg:pb-0 ${
        hideSidebar ? "" : "lg:flex"
      }`}
    >
      <BrandingStyles branding={branding} />
      {!hideSidebar ? <SidebarNav /> : null}

      <div className="flex min-h-screen min-w-0 flex-1 flex-col">
        <ImpersonationBanner />
        <header className="sticky top-0 z-40 border-b border-white/10 bg-white shadow-sm">
          <div className="bg-amber-50 px-4 py-2 text-center text-xs font-medium leading-6 text-amber-950 lg:px-6 sm:text-sm">
            برای استفاده از سیستم پیش‌ثبت‌نام به آدرس{" "}
            <a
              href="https://isold.hcei.ir"
              target="_blank"
              rel="noopener noreferrer"
              className="font-bold underline decoration-amber-700/60 underline-offset-2 hover:text-amber-800"
            >
              isold.hcei.ir
            </a>{" "}
            مراجعه فرمایید
          </div>
          <div className="text-white" style={{ background: "var(--header-gradient)" }}>
            <div className="flex w-full items-center justify-between gap-2 px-4 py-3 lg:px-6">
              <div className="flex min-w-0 flex-1 items-center gap-2">
                {logoSrc ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={logoSrc}
                    alt=""
                    className="h-9 w-9 shrink-0 rounded-xl bg-white/15 object-contain lg:h-8 lg:w-8 lg:rounded-lg"
                  />
                ) : (
                  <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-white/15 lg:hidden">
                    <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor">
                      <path d="M12 3L2 9l10 6 10-6-10-6z" />
                    </svg>
                  </div>
                )}
                <div className="min-w-0">
                  <h1 className="truncate text-sm font-bold lg:text-base">{title ?? branding.admin_title}</h1>
                  <p className="truncate text-[11px] text-white/80 lg:text-xs">
                    {subtitle ?? `${branding.name} · ${roleLabel}`}
                  </p>
                </div>
              </div>
              <div className="flex shrink-0 items-center gap-2">
                <NotificationBell />
                <HeaderUserMenu />
              </div>
            </div>
          </div>
          <Suspense fallback={null}>
            <ShellBreadcrumbBar
              labels={breadcrumbLabels}
              title={title}
              showBack={showBack && !isHome}
            />
          </Suspense>
        </header>

        <main className="w-full flex-1 px-3 pt-3 sm:px-4 lg:px-6 lg:pt-6 xl:px-8">
          {showBack && !isHome ? (
            <div className="hidden lg:block">
              <Suspense fallback={null}>
                <ShellPageBack breadcrumbLabels={breadcrumbLabels} title={title} />
              </Suspense>
            </div>
          ) : null}
          {children}
        </main>
        <BottomNav />
      </div>
    </div>
  );
}

function useShellCrumbs(labels?: BreadcrumbLabels, title?: string) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  return resolveBreadcrumbs(pathname, searchParams, labels ?? {}, getActiveRole(), title);
}

function ShellBreadcrumbBar({
  labels,
  title,
  showBack,
}: {
  labels?: BreadcrumbLabels;
  title?: string;
  showBack?: boolean;
}) {
  const items = useShellCrumbs(labels, title);
  return <Breadcrumb items={items} backHref={showBack ? resolveParentHref(items) : null} />;
}

function ShellPageBack({
  breadcrumbLabels,
  title,
}: {
  breadcrumbLabels?: BreadcrumbLabels;
  title?: string;
}) {
  const items = useShellCrumbs(breadcrumbLabels, title);
  return <PageBackButton href={resolveParentHref(items)} />;
}

export function AuthGuard({ children }: { children: ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem("admin_token");
    if (!token) {
      router.replace("/login");
      return;
    }
    if (pathname === "/change-password") {
      setReady(true);
      return;
    }
    const stored = getStoredUser<{ password_change_required?: boolean }>();
    if (stored?.password_change_required && !isImpersonating()) {
      router.replace("/change-password");
      return;
    }
    if (pathname !== "/select-context" && pathname !== "/login" && !isSessionReady()) {
      router.replace("/select-context");
      return;
    }
    if (pathname === "/select-context" && isSessionReady()) {
      router.replace("/dashboard");
      return;
    }
    setReady(true);
  }, [router, pathname]);

  if (!ready) {
    return (
      <div className="flex min-h-screen items-center justify-center text-sm text-[var(--muted)]">
        در حال بررسی دسترسی…
      </div>
    );
  }

  return <>{children}</>;
}
