"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Globe, LogOut, Menu, Truck, X } from "lucide-react";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { usePortalSession } from "@/features/portal/portal-session";
import { moduleForPath } from "@/config/portal-modules";
import { RouteTitle } from "@/components/providers/route-title";
import { useI18n, useT } from "@/i18n";
import { cn } from "@/lib/cn";

/**
 * The signed-in frame of the store portal: a sidebar listing only what this user may open, a top
 * bar, and a guard that turns away a path the menu would never have offered.
 */
export function PortalShell({ children }: { children: React.ReactNode }) {
  const t = useT();
  const router = useRouter();
  const pathname = usePathname();
  const { dir, locale, setLocale } = useI18n();
  const { user, loading, authenticated, modules, signOut } = usePortalSession();
  const [menuOpen, setMenuOpen] = useState(false);
  const [signingOut, setSigningOut] = useState(false);

  useEffect(() => {
    if (!loading && !authenticated) router.replace("/portal/login");
  }, [loading, authenticated, router]);

  useEffect(() => {
    // Close the mobile drawer after navigating.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setMenuOpen(false);
  }, [pathname]);

  if (loading || !authenticated || !user) {
    return (
      <div className="flex min-h-screen items-center justify-center" role="status" aria-label={t("common.loading")}>
        <span className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  const here = moduleForPath(pathname);
  const permitted = here ? modules.some((module) => module.key === here.key) : true;

  const nav = (
    <nav aria-label={t("common.primaryNav")} className="flex-1 overflow-y-auto px-3 pb-6">
      <ul className="list-none space-y-0.5">
        {modules.map((module) => {
          const active = module.href === "/portal" ? pathname === "/portal" : pathname.startsWith(module.href);
          const Icon = module.icon;
          return (
            <li key={module.key}>
              <Link
                href={module.href}
                aria-current={active ? "page" : undefined}
                className={cn(
                  "group flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
                  active ? "bg-white/10 text-white shadow-inner" : "text-white/70 hover:bg-white/[0.06] hover:text-white",
                )}
              >
                <Icon className={cn("h-[18px] w-[18px]", active ? "text-accent" : "text-inherit")} aria-hidden />
                <span>{t(module.labelKey)}</span>
              </Link>
            </li>
          );
        })}
      </ul>
    </nav>
  );

  const brand = (
    <div className="flex shrink-0 items-center gap-2.5 px-5 pb-5 pt-6">
      <span
        aria-hidden
        className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-primary to-primary-hover text-primary-foreground shadow-sm"
      >
        <Truck className="h-4.5 w-4.5" strokeWidth={2.2} />
      </span>
      <div className="min-w-0 leading-tight">
        <p className="text-sm font-bold tracking-wide text-white">{t("common.appName")}</p>
        <p className="truncate text-[11px] text-white/50">{user.store?.name ?? t("portal.brand")}</p>
      </div>
    </div>
  );

  const sidebarClass =
    "flex h-full w-[260px] flex-col bg-gradient-to-b from-[#120e3c] via-[#1b1255] to-[#0d0a2e] text-white";

  return (
    <div className="flex min-h-screen">
      <RouteTitle label={here ? t(here.labelKey) : undefined} />
      <aside className="fixed inset-y-0 start-0 z-20 hidden lg:block">
        <div className={sidebarClass} dir={dir}>
          {brand}
          {nav}
        </div>
      </aside>

      {menuOpen ? (
        <div className="fixed inset-0 z-40 lg:hidden" role="dialog" aria-modal="true">
          <button
            type="button"
            aria-label={t("common.close")}
            className="absolute inset-0 bg-black/50"
            onClick={() => setMenuOpen(false)}
          />
          <div className={cn(sidebarClass, "relative")} dir={dir}>
            <button
              type="button"
              aria-label={t("common.close")}
              className="absolute end-3 top-4 rounded-md p-1.5 text-white/70 hover:bg-white/10 hover:text-white"
              onClick={() => setMenuOpen(false)}
            >
              <X className="h-5 w-5" />
            </button>
            {brand}
            {nav}
          </div>
        </div>
      ) : null}

      <div className="flex min-w-0 flex-1 flex-col lg:ms-[260px]">
        <header className="sticky top-0 z-10 flex h-14 items-center justify-between gap-3 border-b bg-surface/90 px-4 backdrop-blur sm:px-6">
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="icon"
              className="lg:hidden"
              aria-label={t("common.view")}
              onClick={() => setMenuOpen(true)}
            >
              <Menu className="h-5 w-5" />
            </Button>
            <span className="text-sm font-semibold text-foreground">{t("portal.brand")}</span>
          </div>
          <div className="flex items-center gap-1.5">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setLocale(locale === "en" ? "ar" : "en")}
              aria-label={t("auth.chooseLanguage")}
            >
              <Globe className="h-4 w-4" aria-hidden />
              {locale === "en" ? "العربية" : "English"}
            </Button>
            <span className="hidden text-sm text-muted-foreground sm:inline">{user.name}</span>
            <Button
              variant="ghost"
              size="sm"
              loading={signingOut}
              onClick={() => {
                setSigningOut(true);
                void signOut().finally(() => setSigningOut(false));
              }}
            >
              <LogOut className="h-4 w-4" aria-hidden />
              {t("auth.signOut")}
            </Button>
          </div>
        </header>

        <main className="flex-1 px-4 py-6 sm:px-6 lg:px-8">
          {permitted ? (
            children
          ) : (
            <div className="mx-auto max-w-xl space-y-4">
              <Alert
                variant="warning"
                title={t("portal.noAccess.title")}
              >
                {user.store?.status !== "approved" && (here?.key === "orders" || here?.key === "webhooks" || here?.key === "payments")
                  ? t("portal.noAccess.pending")
                  : t("portal.noAccess.owner")}
              </Alert>
              <Button onClick={() => router.replace("/portal")}>
                {t("portal.noAccess.back")}
              </Button>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
