import Link from "next/link";
import Image from "next/image";
import { Suspense, type ReactNode } from "react";
import { ROLES, ROUTES } from "@/lib/constants";
import { env } from "@/lib/env";
import { getRegionCodes, getRegionLabels } from "@/lib/regions";
import type { ViewerContext } from "@/lib/types";
import { signOutAction } from "@/app/(app)/actions";
import { SidebarNav } from "@/components/layout/sidebar-nav";
import { AdminScopeBar } from "@/components/layout/admin-scope-bar";
import { AdminSidebarBrand } from "@/components/layout/admin-sidebar-brand";
import { FormSubmitButton } from "@/components/ui/form-submit-button";

export function AppShell({
  children,
  viewer,
}: {
  children: ReactNode;
  viewer: ViewerContext;
}) {
  const shared = [
    { href: ROUTES.dashboard, label: "VAE Dashboard" },
    { href: ROUTES.metadata, label: "VAE Metadata" },
  ];

  const navItems =
    viewer.role === ROLES.admin
      ? [...shared.slice(0, 1), { href: ROUTES.upload, label: "New Data Import" }, ...shared.slice(1)]
      : shared;
  const regionLabels = getRegionLabels(viewer.allowedCountries);
  const regionCodes = getRegionCodes();
  const primaryRegionCode = regionLabels[0]?.split(":")[0] ?? "";
  const heading =
    viewer.role === ROLES.affiliate && primaryRegionCode
      ? `${primaryRegionCode} VAE Dashboard`
      : "ALL VAE Dashboards";
  const hideSubHeading = primaryRegionCode === "OPEL";
  const subHeading =
    viewer.role === ROLES.affiliate && regionLabels.length > 0
      ? regionLabels[0]
      : "Global Otsuka VEEVA Performance";

  return (
    <div className="min-h-screen">
      <div className="grid min-h-screen grid-cols-1 gap-0 lg:grid-cols-[330px_minmax(0,1fr)]">
        <aside className="flex flex-col border-r border-[#25589a] bg-[linear-gradient(180deg,#2C6BB6_0%,#255ea3_65%,#214f89_100%)] p-6 text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.2),0_22px_45px_-28px_rgba(8,28,56,0.85)] lg:sticky lg:top-0 lg:h-screen lg:overflow-auto lg:rounded-r-[28px]">
          <div>
            <Link href={ROUTES.dashboard} className="block">
              {viewer.role === ROLES.admin ? (
                <Suspense
                  fallback={
                    <>
                      <h1 className="mt-3 text-5xl font-black leading-[0.95] tracking-tight text-white">
                        {heading}
                      </h1>
                      {hideSubHeading ? null : (
                        <p className="mt-2 text-sm font-semibold uppercase tracking-[0.14em] text-[#F7993A]">
                          {subHeading}
                        </p>
                      )}
                    </>
                  }
                >
                  <AdminSidebarBrand scopes={regionCodes} />
                </Suspense>
              ) : (
                <>
                  <h1 className="mt-3 text-5xl font-black leading-[0.95] tracking-tight text-white">
                    {heading}
                  </h1>
                  {hideSubHeading ? null : (
                    <p className="mt-2 text-sm font-semibold uppercase tracking-[0.14em] text-[#F7993A]">
                      {subHeading}
                    </p>
                  )}
                </>
              )}
            </Link>

            <div className="mt-8 px-1">
              <Suspense
                fallback={
                  <nav className="space-y-2">
                    {navItems.map((item) => (
                      <Link
                        key={item.href}
                        href={item.href}
                        className="group block rounded-2xl px-4 py-3 text-sm font-medium text-blue-100/95 transition duration-200 hover:bg-white/10 hover:text-white"
                      >
                        <span className="flex items-center gap-2.5">
                          <span className="h-2.5 w-2.5 rounded-full bg-[#F7993A] opacity-80 group-hover:opacity-100" />
                          {item.label}
                        </span>
                      </Link>
                    ))}
                  </nav>
                }
              >
                <SidebarNav items={navItems} />
              </Suspense>
            </div>

            <form action={signOutAction} className="mt-8">
              <FormSubmitButton
                idleLabel={env.disableAuth ? "Switch profile" : "Sign out"}
                pendingLabel={env.disableAuth ? "Switching..." : "Signing out..."}
                variant="secondary"
                className="w-full border-white/25 bg-white/10 text-white hover:bg-white/18"
              />
            </form>

          </div>

          <div className="mt-auto pt-8">
            <div className="flex w-full items-center justify-center py-2">
              <Image
                src="/brand/otsuka-white_766.png"
                alt="Otsuka"
                width={220}
                height={113}
                className="h-auto w-[74%] max-w-[190px] opacity-95"
                priority
              />
            </div>
          </div>
        </aside>

        <main className="min-w-0 space-y-4 px-3 py-3 sm:px-4 sm:py-4 lg:px-6 lg:py-6">
          <div className="mx-auto w-full max-w-[1650px] space-y-4">
            {viewer.role === ROLES.admin ? (
              <Suspense
                fallback={
                  <div className="rounded-2xl border border-slate-900/20 bg-[linear-gradient(180deg,#0f172a_0%,#111e36_100%)] px-3 py-2 text-sm text-blue-100">
                    Loading admin scope...
                  </div>
                }
              >
                <AdminScopeBar scopes={regionCodes} />
              </Suspense>
            ) : null}
            {children}
          </div>
        </main>
      </div>
    </div>
  );
}
