"use client";

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

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: "/users", label: "Benutzer", icon: Shield, adminOnly: true }
];

export function AppShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const auth = useAuth();

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

  return (
    <div className="min-h-screen bg-background text-text">
      <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>
        <nav className="space-y-1">
          {navigation.map((item, index) => {
            const Icon = item.icon;
            if ("adminOnly" in item && item.adminOnly && auth.user?.role !== "admin") {
              return null;
            }
            const active = pathname === item.href || pathname.startsWith(`${item.href}/`);
            return (
              <Link
                key={`${item.label}-${index}`}
                href={item.href}
                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>
  );
}
