"use client";
// src/components/layout/Sidebar.tsx
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { useLanguage } from "@/i18n/LanguageContext";
import { cn, getInitials } from "@/lib/utils";
import { hasPermission } from "@/lib/permissions";
import type { Permission } from "@/lib/permissions";
import {
  LayoutDashboard, TrendingUp, Users, Building2, Briefcase,
  CheckSquare, Activity, Ticket, BarChart3, Settings, UserCog,
  ChevronLeft, ChevronRight, LogOut, FileText, Receipt,
  Package, Shield, ShoppingCart, CalendarDays, Goal, ImageIcon, Repeat, FileSignature,
} from "lucide-react";
import type { TranslationKey } from "@/i18n/translations";
import { ROLE_LABEL_KEYS } from "@/lib/roleLabels";

interface NavItem {
  href: string;
  icon: React.ReactNode;
  labelKey: TranslationKey;
  permission?: Permission;
}

const NAV_GROUPS: { groupKey?: TranslationKey; items: NavItem[] }[] = [
  {
    items: [
      { href: "/dashboard", icon: <LayoutDashboard className="w-4 h-4" />, labelKey: "nav.dashboard" },
    ],
  },
  {
    groupKey: "nav.groupCrm",
    items: [
      { href: "/leads", icon: <TrendingUp className="w-4 h-4" />, labelKey: "nav.leads", permission: "leads:read" },
      { href: "/customers", icon: <Users className="w-4 h-4" />, labelKey: "nav.customers", permission: "customers:read" },
      { href: "/companies", icon: <Building2 className="w-4 h-4" />, labelKey: "nav.companies", permission: "companies:read" },
      { href: "/deals", icon: <Briefcase className="w-4 h-4" />, labelKey: "nav.deals", permission: "deals:read" },
    ],
  },
  {
    groupKey: "nav.groupFinance",
    items: [
      { href: "/quotes", icon: <FileText className="w-4 h-4" />, labelKey: "nav.quotes", permission: "quotes:read" },
      { href: "/invoices", icon: <Receipt className="w-4 h-4" />, labelKey: "nav.invoices", permission: "invoices:read" },
      { href: "/products", icon: <Package className="w-4 h-4" />, labelKey: "nav.products", permission: "deals:read" },
      { href: "/subscriptions", icon: <Repeat className="w-4 h-4" />, labelKey: "nav.subscriptions", permission: "subscriptions:read" },
      { href: "/contracts", icon: <FileSignature className="w-4 h-4" />, labelKey: "nav.contracts", permission: "contracts:read" },
    ],
  },
  {
    groupKey: "nav.groupWork",
    items: [
      { href: "/tasks", icon: <CheckSquare className="w-4 h-4" />, labelKey: "nav.tasks", permission: "tasks:read" },
      { href: "/activities", icon: <Activity className="w-4 h-4" />, labelKey: "nav.activities", permission: "activities:read" },
      { href: "/tickets", icon: <Ticket className="w-4 h-4" />, labelKey: "nav.tickets", permission: "tickets:read" },
    ],
  },
  {
    groupKey: "nav.groupInsights",
    items: [
      { href: "/reports", icon: <BarChart3 className="w-4 h-4" />, labelKey: "nav.reports", permission: "reports:read" },
    ],
  },
  {
    groupKey: "nav.groupUtilities",
    items: [
      { href: "/utilities/media", icon: <ImageIcon className="w-4 h-4" />, labelKey: "nav.utilitiesMedia", permission: "media:read" },
      { href: "/utilities/calendar", icon: <CalendarDays className="w-4 h-4" />, labelKey: "nav.utilitiesCalendar" },
      { href: "/utilities/goals", icon: <Goal className="w-4 h-4" />, labelKey: "nav.utilitiesGoals", permission: "goals:read" },
    ],
  },
  {
    groupKey: "nav.groupAdmin",
    items: [
      { href: "/users", icon: <UserCog className="w-4 h-4" />, labelKey: "nav.users", permission: "users:read" },
      { href: "/audit-logs", icon: <Shield className="w-4 h-4" />, labelKey: "nav.auditLogs", permission: "settings:read" },
      { href: "/settings", icon: <Settings className="w-4 h-4" />, labelKey: "nav.settings", permission: "settings:read" },
    ],
  },
];

interface SidebarProps {
  collapsed: boolean;
  onToggle: () => void;
}

export function Sidebar({ collapsed, onToggle }: SidebarProps) {
  const pathname = usePathname();
  const { user, logout } = useAuth();
  const { t, isRTL } = useLanguage();

  const isActive = (href: string) =>
    href === "/dashboard" ? pathname === href : pathname.startsWith(href);

  const canAccess = (item: NavItem) => {
    if (!item.permission) return true;
    if (!user) return false;
    return hasPermission(user.role, item.permission);
  };

  const getLabel = (item: NavItem) => t(item.labelKey);

  const roleDisplay = user
    ? ROLE_LABEL_KEYS[user.role]
      ? t(ROLE_LABEL_KEYS[user.role])
      : user.role.replace(/_/g, " ")
    : "";

  return (
    <aside
      className={cn(
        "fixed top-0 bottom-0 z-40 flex flex-col bg-[hsl(var(--sidebar))] border-[hsl(var(--sidebar-border))] sidebar-transition",
        collapsed ? "w-[68px]" : "w-[260px]",
        isRTL ? "right-0 border-l" : "left-0 border-r"
      )}
    >
      {/* Logo */}
      <div className={cn(
        "h-[60px] flex items-center border-b border-[hsl(var(--sidebar-border))] flex-shrink-0",
        collapsed ? "justify-center px-4" : "px-4 gap-3"
      )}>
        <div className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center flex-shrink-0">
          <ShoppingCart className="w-4 h-4 text-white" />
        </div>
        {!collapsed && (
          <div>
            <div className="font-bold text-white text-sm tracking-tight">CRM Pro</div>
            <div className="text-[10px] text-[hsl(var(--sidebar-foreground))] opacity-70">
              {t("sidebar.tagline")}
            </div>
          </div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden py-3 px-2 space-y-4">
        {NAV_GROUPS.map((group, gi) => {
          const accessibleItems = group.items.filter(canAccess);
          if (!accessibleItems.length) return null;

          return (
            <div key={gi}>
              {/* Group label */}
              {!collapsed && group.groupKey && (
                <div className="px-2 mb-1">
                  <p className="text-[10px] font-semibold uppercase tracking-widest text-[hsl(var(--sidebar-foreground))] opacity-50">
                    {t(group.groupKey)}
                  </p>
                </div>
              )}

              {/* Items */}
              <div className="space-y-0.5">
                {accessibleItems.map((item) => {
                  const active = isActive(item.href);
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      title={collapsed ? getLabel(item) : undefined}
                      className={cn(
                        "flex items-center gap-3 px-2.5 py-2 rounded-lg text-sm font-medium transition-all duration-100 group relative",
                        active
                          ? "bg-primary/20 text-white"
                          : "text-[hsl(var(--sidebar-foreground))] hover:bg-[hsl(var(--sidebar-accent))] hover:text-white",
                        collapsed && "justify-center"
                      )}
                    >
                      <span className={cn("flex-shrink-0 transition-colors", active ? "text-primary" : "opacity-70 group-hover:opacity-100")}>
                        {item.icon}
                      </span>
                      {!collapsed && (
                        <span className="truncate">{getLabel(item)}</span>
                      )}
                      {active && !collapsed && (
                        <span className={cn("absolute w-1 h-5 rounded-full bg-primary", isRTL ? "left-0" : "right-0")} />
                      )}
                      {/* Tooltip */}
                      {collapsed && (
                        <span className={cn(
                          "absolute px-2 py-1 bg-gray-900 text-white text-xs rounded-lg whitespace-nowrap opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-50 shadow-lg",
                          isRTL ? "right-full mr-2" : "left-full ml-2"
                        )}>
                          {getLabel(item)}
                        </span>
                      )}
                    </Link>
                  );
                })}
              </div>
            </div>
          );
        })}
      </nav>

      {/* User */}
      <div className="border-t border-[hsl(var(--sidebar-border))] p-3 flex-shrink-0">
        <div className={cn("flex items-center gap-2.5", collapsed && "justify-center")}>
          <div className="w-8 h-8 rounded-full bg-primary/30 flex items-center justify-center flex-shrink-0 text-white text-xs font-bold">
            {user ? getInitials(user.name) : "U"}
          </div>
          {!collapsed && user && (
            <>
              <div className="flex-1 min-w-0">
                <div className="text-xs font-semibold text-white truncate">{user.name}</div>
                <div className="text-[10px] text-[hsl(var(--sidebar-foreground))] opacity-60 truncate">
                  {roleDisplay}
                </div>
              </div>
              <button
                onClick={() => logout()}
                className="text-[hsl(var(--sidebar-foreground))] hover:text-white transition-colors opacity-60 hover:opacity-100 flex-shrink-0"
                title={t("auth.logout")}
              >
                <LogOut className="w-4 h-4" />
              </button>
            </>
          )}
        </div>
      </div>

      {/* Collapse toggle */}
      <button
        type="button"
        onClick={onToggle}
        aria-label={collapsed ? t("sidebar.expand") : t("sidebar.collapse")}
        className={cn(
          "absolute top-[68px] w-5 h-5 rounded-full bg-card border border-border flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors z-50 shadow-sm",
          isRTL ? "-left-2.5" : "-right-2.5"
        )}
      >
        {(collapsed && !isRTL) || (!collapsed && isRTL)
          ? <ChevronRight className="w-3 h-3" />
          : <ChevronLeft className="w-3 h-3" />}
      </button>
    </aside>
  );
}
