"use client";

import {
  Building2,
  ClipboardCheck,
  ClipboardPlus,
  FileArchive,
  FileCog,
  Gauge,
  LayoutDashboard,
  LogOut,
  MapPin,
  Shield,
  Stethoscope,
  UserRound
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
import { useAuth } from "@/components/auth";
import { BrandLogo } from "@/components/brand/brand-logo";

const QUICKSTART_HREF = "/validations/quick-start";
const quickstartRoles = ["admin", "pruefer", "mitarbeiter"];

const navigation = [
  { href: "/dashboard", label: "Dashboard", icon: LayoutDashboard },
  { href: "/customers", label: "Kunden", icon: Building2 },
  { href: "/locations", label: "Standorte", icon: MapPin },
  { href: "/contacts", label: "Ansprechpartner", icon: UserRound },
  { href: "/devices", label: "Geraete", icon: Stethoscope },
  { href: "/equipment", label: "Pruefmittel", icon: Gauge },
  { href: "/validations", label: "Validierungen", icon: ClipboardCheck },
  { href: "/documents", label: "Dokumente", icon: FileArchive },
  { href: "/settings/report-layout", label: "Berichtseinstellungen", icon: FileCog, adminOnly: true },
  { href: "/users", label: "Benutzer", icon: Shield, adminOnly: true }
];

function canStartValidation(role?: string) {
  return role ? quickstartRoles.includes(role) : false;
}

function isActiveRoute(pathname: string, href: string) {
  if (href === "/validations") {
    return pathname === href || (pathname.startsWith(`${href}/`) && pathname !== QUICKSTART_HREF);
  }
  return pathname === href || pathname.startsWith(`${href}/`);
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const auth = useAuth();
  const showQuickstart = canStartValidation(auth.user?.role);
  const quickstartActive = pathname === QUICKSTART_HREF;

  useEffect(() => {
    if (auth.user?.must_change_password && pathname !== "/profile/security") {
      window.location.replace("/profile/security");
    }
  }, [auth.user?.must_change_password, pathname]);

  return (
    <div className="min-h-screen bg-background text-text">
      <header className="sticky top-0 z-40 border-b border-border bg-surface/95 px-4 py-4 shadow-soft backdrop-blur lg:hidden">
        <div className="flex items-center justify-between gap-3">
          <BrandLogo compact />
        </div>
        {showQuickstart ? (
          <Link
            href={QUICKSTART_HREF}
            aria-current={quickstartActive ? "page" : undefined}
            className={`mt-4 flex min-h-12 w-full items-center justify-center gap-3 rounded-lg border px-4 text-sm font-bold shadow-soft transition hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-[0.98] ${
              quickstartActive
                ? "border-primary-dark bg-primary-dark text-white"
                : "border-primary bg-primary text-white hover:bg-primary-dark"
            }`}
          >
            <ClipboardPlus className="h-5 w-5" />
            <span>Neue Validierung starten</span>
          </Link>
        ) : null}
        <nav className="mt-4 flex gap-2 overflow-x-auto pb-1">
          {navigation.map((item, index) => {
            const Icon = item.icon;
            if ("adminOnly" in item && item.adminOnly && auth.user?.role !== "admin") {
              return null;
            }
            const active = isActiveRoute(pathname, item.href);
            return (
              <Link
                key={`${item.label}-mobile-${index}`}
                href={item.href}
                aria-current={active ? "page" : undefined}
                className={`flex min-h-11 shrink-0 items-center gap-2 rounded-lg border px-3 text-sm font-medium transition hover:shadow-soft focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-[0.98] ${
                  active
                    ? "border-accent bg-accent/35 text-primary-dark"
                    : "border-border bg-white text-text-light hover:bg-background hover:text-text"
                }`}
              >
                <Icon className="h-4 w-4" />
                <span>{item.label}</span>
              </Link>
            );
          })}
        </nav>
      </header>
      <aside className="fixed inset-y-0 left-0 z-30 hidden w-72 border-r border-border bg-surface px-5 py-6 lg:block">
        <div className="mb-8">
          <BrandLogo compact />
        </div>
        {showQuickstart ? (
          <Link
            href={QUICKSTART_HREF}
            aria-current={quickstartActive ? "page" : undefined}
            className={`mb-6 flex min-h-12 w-full items-center justify-center gap-3 rounded-lg border px-4 text-sm font-bold shadow-soft transition hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-[0.98] ${
              quickstartActive
                ? "border-primary-dark bg-primary-dark text-white"
                : "border-primary bg-primary text-white hover:bg-primary-dark"
            }`}
          >
            <ClipboardPlus className="h-5 w-5" />
            <span>Neue Validierung starten</span>
          </Link>
        ) : null}
        <nav className="space-y-1 pb-20">
          {navigation.map((item, index) => {
            const Icon = item.icon;
            if ("adminOnly" in item && item.adminOnly && auth.user?.role !== "admin") {
              return null;
            }
            const active = isActiveRoute(pathname, item.href);
            return (
              <Link
                key={`${item.label}-${index}`}
                href={item.href}
                aria-current={active ? "page" : undefined}
                className={`flex h-11 items-center gap-3 rounded-lg px-3 text-sm font-medium transition hover:shadow-soft active:scale-[0.98] ${
                  active ? "bg-accent/35 text-primary-dark" : "text-text-light hover:bg-background hover:text-text"
                }`}
              >
                <Icon className="h-4 w-4" />
                <span>{item.label}</span>
              </Link>
            );
          })}
        </nav>
        <button
          type="button"
          onClick={auth.logout}
          className="btn btn-primary absolute bottom-6 left-5 right-5 h-11 text-sm"
        >
          <LogOut className="h-4 w-4" />
          Logout
        </button>
      </aside>
      <main className="lg:pl-72">
        <div className="mx-auto min-h-screen max-w-7xl px-4 py-5 sm:px-6 lg:px-10 lg:py-8">{children}</div>
      </main>
    </div>
  );
}
