"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import {
  Home,
  UserPlus,
  UserMinus,
  ArrowLeftRight,
  Users,
  GitBranch,
  CheckSquare,
  Laptop,
  FileText,
  Plug,
  BarChart3,
  ShieldCheck,
  Settings,
  PanelLeftClose,
  PanelLeftOpen,
  X,
  Layers,
} from "lucide-react";
import { SIDEBAR_NAVIGATION, type NavIconName } from "@/lib/config/navigation";
import { cn, getInitials } from "@/lib/utils";

const ICON_MAP: Record<NavIconName, React.ComponentType<{ className?: string }>> = {
  home: Home,
  "user-plus": UserPlus,
  "user-minus": UserMinus,
  "arrow-left-right": ArrowLeftRight,
  users: Users,
  "git-branch": GitBranch,
  "check-square": CheckSquare,
  laptop: Laptop,
  "file-text": FileText,
  plug: Plug,
  "bar-chart-3": BarChart3,
  "shield-check": ShieldCheck,
  settings: Settings,
};

interface SidebarProps {
  collapsed: boolean;
  onToggleCollapse: () => void;
  mobileOpen: boolean;
  onCloseMobile: () => void;
  user: {
    name: string;
    roleLabel: string;
    email: string;
  };
  overdueTasksCount?: number;
}

export function Sidebar({
  collapsed,
  onToggleCollapse,
  mobileOpen,
  onCloseMobile,
  user,
  overdueTasksCount = 0,
}: SidebarProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const activeCompany = searchParams.get("company");

  const withCompanyParam = (href: string) => {
    if (!activeCompany || activeCompany === "ALL") return href;
    return `${href}?company=${encodeURIComponent(activeCompany)}`;
  };

  const groups: Array<{ key: "core" | "operations" | "governance"; label: string }> = [
    { key: "core", label: "Lifecycle" },
    { key: "operations", label: "Operations" },
    { key: "governance", label: "Governance" },
  ];

  const navContent = (isMobile: boolean) => {
    const isCompact = !isMobile && collapsed;

    return (
      <div className="flex h-full flex-col bg-white">
        {/* Brand Header */}
        <div
          className={cn(
            "flex h-[60px] shrink-0 items-center border-b border-[#E5E7EB] px-3.5",
            isCompact ? "justify-center" : "justify-between"
          )}
        >
          <Link
            href={withCompanyParam("/")}
            onClick={isMobile ? onCloseMobile : undefined}
            className="flex items-center gap-2.5 overflow-hidden"
          >
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand text-white shadow-subtle">
              <Layers className="h-4 w-4" />
            </div>
            {!isCompact && (
              <div className="flex flex-col leading-tight">
                <span className="text-sm font-semibold tracking-tight text-[#111827]">
                  PEOPLEFLOW
                </span>
                <span className="text-[10px] font-medium tracking-wide text-[#64748B]">
                  SMC CEMENT GROUP
                </span>
              </div>
            )}
          </Link>

          {isMobile ? (
            <button
              type="button"
              onClick={onCloseMobile}
              aria-label="Close navigation menu"
              className="rounded-lg p-1.5 text-[#64748B] hover:bg-[#F1F5F9] hover:text-[#111827]"
            >
              <X className="h-4 w-4" />
            </button>
          ) : (
            !isCompact && (
              <button
                type="button"
                onClick={onToggleCollapse}
                title="Collapse sidebar"
                aria-label="Collapse sidebar"
                className="rounded-lg p-1.5 text-[#64748B] transition-colors hover:bg-[#F1F5F9] hover:text-[#111827]"
              >
                <PanelLeftClose className="h-4 w-4" />
              </button>
            )
          )}
        </div>

        {/* Navigation Links */}
        <nav
          aria-label="Primary Sidebar Navigation"
          className="flex-1 space-y-5 overflow-y-auto px-2.5 py-4"
        >
          {groups.map((group) => {
            const items = SIDEBAR_NAVIGATION.filter((n) => n.group === group.key);
            return (
              <div key={group.key} className="space-y-1">
                {!isCompact && (
                  <p className="px-2.5 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[#94A3B8]">
                    {group.label}
                  </p>
                )}
                {items.map((item) => {
                  const Icon = ICON_MAP[item.icon];
                  const isActive =
                    item.href === "/"
                      ? pathname === "/"
                      : pathname === item.href || pathname.startsWith(`${item.href}/`);

                  return (
                    <Link
                      key={item.href}
                      href={withCompanyParam(item.href)}
                      onClick={isMobile ? onCloseMobile : undefined}
                      title={isCompact ? item.label : undefined}
                      className={cn(
                        "group flex items-center rounded-lg text-[13px] font-medium transition-colors",
                        isCompact ? "justify-center px-2 py-2.5" : "justify-between px-2.5 py-2",
                        isActive
                          ? "bg-brand-soft text-brand"
                          : "text-[#475569] hover:bg-[#F8FAFC] hover:text-[#111827]"
                      )}
                    >
                      <span className="flex items-center gap-2.5 truncate">
                        <Icon
                          className={cn(
                            "h-4 w-4 shrink-0",
                            isActive
                              ? "text-brand"
                              : "text-[#64748B] group-hover:text-[#111827]"
                          )}
                        />
                        {!isCompact && <span className="truncate">{item.label}</span>}
                      </span>

                      {!isCompact && item.badgeKey === "overdueTasks" && overdueTasksCount > 0 && (
                        <span className="rounded-full bg-red-50 px-1.5 py-0.5 text-[10px] font-semibold text-red-600">
                          {overdueTasksCount}
                        </span>
                      )}
                    </Link>
                  );
                })}
              </div>
            );
          })}
        </nav>

        {/* Expand button when collapsed */}
        {isCompact && (
          <div className="flex justify-center border-t border-[#E5E7EB] py-2">
            <button
              type="button"
              onClick={onToggleCollapse}
              title="Expand sidebar"
              aria-label="Expand sidebar"
              className="rounded-lg p-2 text-[#64748B] transition-colors hover:bg-[#F1F5F9] hover:text-[#111827]"
            >
              <PanelLeftOpen className="h-4 w-4" />
            </button>
          </div>
        )}

        {/* Bottom User Profile */}
        <div className="shrink-0 border-t border-[#E5E7EB] p-3">
          <Link
            href="/settings"
            onClick={isMobile ? onCloseMobile : undefined}
            className={cn(
              "flex items-center rounded-lg p-1.5 transition-colors hover:bg-[#F8FAFC]",
              isCompact ? "justify-center" : "gap-2.5"
            )}
          >
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand text-xs font-semibold text-white">
              {getInitials(user.name)}
            </div>
            {!isCompact && (
              <div className="min-w-0 flex-1">
                <p className="truncate text-xs font-semibold text-[#111827]">{user.name}</p>
                <p className="truncate text-[11px] text-[#64748B]">{user.roleLabel}</p>
              </div>
            )}
          </Link>
        </div>
      </div>
    );
  };

  return (
    <>
      {/* Desktop Persistent Sidebar */}
      <aside
        className={cn(
          "hidden shrink-0 border-r border-[#E5E7EB] bg-white transition-[width] duration-200 lg:block",
          collapsed ? "w-[68px]" : "w-[248px]"
        )}
      >
        <div className="sticky top-0 h-screen">{navContent(false)}</div>
      </aside>

      {/* Mobile Drawer Overlay */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 flex lg:hidden">
          <div
            className="fixed inset-0 bg-slate-900/40 backdrop-blur-[1px]"
            onClick={onCloseMobile}
            aria-hidden="true"
          />
          <aside className="relative z-10 h-full w-[264px] border-r border-[#E5E7EB] bg-white shadow-elevated">
            {navContent(true)}
          </aside>
        </div>
      )}
    </>
  );
}
