import { type ReactNode, useMemo, useState, useEffect } from "react";
import { NavLink, useLocation } from "react-router-dom";

import { usePortalSession } from "../context/PortalSessionContext";
import {
  adminWorkspaceLinks,
  getVisibleTenantWorkspaceLinks,
  getModuleWorkspaceHref,
  getWorkspaceTitle,
  type WorkspaceLink,
} from "../config/workspace";

interface AppShellProps {
  children: ReactNode;
}

const navIcons: Record<string, string> = {
  home: "M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-4 0a1 1 0 01-1-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 01-1 1",
  timeclock: "M12 8v5l3 2m6-3a9 9 0 11-18 0 9 9 0 0118 0z",
  dashboard: "M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z",
  inventory: "M3 7.5l9-4 9 4m-18 0v9l9 4 9-4v-9M3 7.5l9 4m9-4l-9 4m0 0v9",
  ordini: "M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01",
  prenotazioni: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z",
  documents: "M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z",
  menu: "M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253",
  homemade: "M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z",
  account: "M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z",
  admin: "M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z",
};

function NavIcon({ id }: { id: string }) {
  const d = navIcons[id];
  if (!d) return null;
  return (
    <svg className="nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
      <path d={d} />
    </svg>
  );
}

export function AppShell({ children }: AppShellProps) {
  const location = useLocation();
  const { tenantContext, currentUser, hasStoredAdminSession, logout, platformAdmin, returnToAdmin } = usePortalSession();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // Close sidebar on route change
  useEffect(() => {
    setSidebarOpen(false);
  }, [location.pathname]);

  // Prevent body scroll when sidebar is open on mobile
  useEffect(() => {
    if (sidebarOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [sidebarOpen]);

  if (!tenantContext) {
    return null;
  }

  const isPlatformConsole = currentUser?.role === "super_admin" && !platformAdmin?.is_impersonating;
  const isImpersonating = Boolean(platformAdmin?.is_impersonating);
  const venueName = isPlatformConsole
    ? "Pannello Admin"
    : tenantContext.venues[0]?.name ?? tenantContext.tenant.name;
  const links = isPlatformConsole
    ? adminWorkspaceLinks
    : getVisibleTenantWorkspaceLinks(currentUser?.role, currentUser?.permissions);
  const currentViewTitle = useMemo(() => {
    return getWorkspaceTitle(location.pathname, isPlatformConsole);
  }, [isPlatformConsole, location.pathname]);

  return (
    <div className="app-layout">
      {/* Mobile top bar */}
      <header className="topbar">
        <button
          type="button"
          className="hamburger"
          onClick={() => setSidebarOpen(true)}
          aria-label="Apri menu"
        >
          <span /><span /><span />
        </button>
        <div className="topbar-brand">
          <span className="topbar-logo">PU</span>
          <span className="topbar-title">{currentViewTitle}</span>
        </div>
      </header>

      {/* Sidebar backdrop for mobile */}
      {sidebarOpen && (
        <div
          className="sidebar-backdrop"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside className={`sidebar${sidebarOpen ? " is-open" : ""}`}>
        <div className="sidebar-inner">
          <div className="sidebar-head">
            <div className="sidebar-brand">
              <div className="sidebar-brand-mark">PU</div>
              <div className="sidebar-brand-text">
                <strong>PowerUp</strong>
                <span>{isPlatformConsole ? "Console" : "Suite"}</span>
              </div>
            </div>
            <button
              type="button"
              className="sidebar-close"
              onClick={() => setSidebarOpen(false)}
              aria-label="Chiudi menu"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round">
                <path d="M18 6L6 18M6 6l12 12" />
              </svg>
            </button>
          </div>

          <div className="sidebar-venue">
            <span className="sidebar-venue-label">{isPlatformConsole ? "Sessione" : "Locale"}</span>
            <strong className="sidebar-venue-name">{venueName}</strong>
            <small className="sidebar-venue-user">{currentUser?.username || currentUser?.email}</small>
          </div>

          <nav className="sidebar-nav" aria-label="Navigazione principale">
            {links.map((link) => renderNavLink(link, () => setSidebarOpen(false)))}
          </nav>

          <div className="sidebar-footer">
            {isImpersonating && hasStoredAdminSession ? (
              <button type="button" className="sidebar-action-btn" onClick={() => void returnToAdmin()}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
                  <path d="M11 17l-5-5m0 0l5-5m-5 5h12" />
                </svg>
                Torna admin
              </button>
            ) : null}
            <button type="button" className="sidebar-action-btn sidebar-logout" onClick={() => void logout()}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
                <path d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
              </svg>
              Esci
            </button>
          </div>
        </div>
      </aside>

      {/* Main content */}
      <main className="main-content">
        {children}
      </main>
    </div>
  );
}

function renderNavLink(link: WorkspaceLink, onClick: () => void) {
  const to = link.kind === "internal" ? link.to : getModuleWorkspaceHref(link.moduleKey);

  return (
    <NavLink
      key={link.id}
      to={to}
      onClick={onClick}
      className={({ isActive }) => `sidebar-link${isActive ? " is-active" : ""}`}
    >
      <NavIcon id={link.id} />
      <span className="sidebar-link-label">{link.label}</span>
    </NavLink>
  );
}
