import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import {
  LayoutDashboard,
  CreditCard,
  Users,
  Package,
  ShoppingCart,
  Truck,
  UserCheck,
  Receipt,
  BarChart3,
  Settings,
  LogOut,
  Store,
  Languages,
  ChevronDown,
  ChevronRight,
  RotateCcw,
  ClipboardList,
  ArrowLeftRight,
  Wallet,
  Banknote,
  ShieldCheck,
  Warehouse,
  DatabaseBackup,
  ScrollText,
  Building2,
  Tag,
  Bell,
  TrendingUp,
  TrendingDown,
  Crown,
  MessageSquare,
  FileText,
  
} from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { useLanguage } from "@/hooks/use-language";
import { usePermissions } from "@/hooks/use-permissions";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { CompanyLogo } from "@/components/CompanyLogo";

type NavItem = {
  to?: string;
  icon: React.ElementType;
  labelKey: string;
  children?: { to: string; labelKey: string }[];
  requiredPermissions?: string[];
  adminOnly?: boolean;
};

const navItems: NavItem[] = [
  { to: "/", icon: LayoutDashboard, labelKey: "dashboard" },
  { to: "/management", icon: Users, labelKey: "management" },
  {
    icon: CreditCard,
    labelKey: "account",
    children: [
      { to: "/expenses", labelKey: "expenses" },
      { to: "/incomes", labelKey: "incomes" },
      { to: "/transaction-categories", labelKey: "transactionCategories" },
      { to: "/daily-cash-closing", labelKey: "dailyCashClosing" },
    ],
  },
  {
    icon: Package,
    labelKey: "product",
    children: [
      { to: "/products", labelKey: "productList" },
      { to: "/products/add", labelKey: "addProduct" },
      { to: "/product-types", labelKey: "productTypes" },
      { to: "/units", labelKey: "units" },
      { to: "/categories", labelKey: "categories" },
      { to: "/subcategories", labelKey: "subCategories" },
      { to: "/brands", labelKey: "brands" },
    ],
  },
  {
    icon: ShoppingCart,
    labelKey: "purchase",
    children: [
      { to: "/purchases", labelKey: "purchaseList" },
      { to: "/purchases/add", labelKey: "addPurchase" },
    ],
    requiredPermissions: ["view_products"],
  },
  {
    icon: Truck,
    labelKey: "suppliers",
    children: [
      { to: "/suppliers", labelKey: "supplierList" },
      { to: "/suppliers/add", labelKey: "addSupplier" },
    ],
  },
  { to: "/customers", icon: UserCheck, labelKey: "customers" },
  { to: "/customer-segments", icon: Crown, labelKey: "customerSegments" },
  {
    icon: Users,
    labelKey: "staff",
    children: [
      { to: "/staff", labelKey: "Staff List" },
      { to: "/departments", labelKey: "Departments" },
      { to: "/staff-attendance", labelKey: "Attendance" },
      { to: "/staff-payroll", labelKey: "Payroll" },
    ],
  },
  {
    icon: Receipt,
    labelKey: "sales",
    children: [
      { to: "/sales", labelKey: "saleList" },
      { to: "/sales/create", labelKey: "addNewSale" },
    ],
  },
  {
    icon: RotateCcw,
    labelKey: "returnLabel",
    children: [
      { to: "/returns", labelKey: "returnList" },
    ],
  },
  {
    icon: Warehouse,
    labelKey: "godown",
    children: [
      { to: "/godowns", labelKey: "godownList" },
      { to: "/godowns/add", labelKey: "addGodown" },
      { to: "/godowns/transfer", labelKey: "stockTransfer" },
    ],
  },
  {
    icon: ClipboardList,
    labelKey: "salesOrder",
    children: [
      { to: "/sales-orders", labelKey: "salesOrderList" },
      { to: "/sales-orders/create", labelKey: "addSalesOrder" },
    ],
  },
  { to: "/quotations", icon: FileText, labelKey: "quotations" },
  {
    icon: ArrowLeftRight,
    labelKey: "transfer",
    children: [
      { to: "/transfers", labelKey: "transferList" },
      { to: "/transfers/create", labelKey: "createTransfer" },
    ],
  },
  { to: "/notifications", icon: Bell, labelKey: "notifications" },
  { to: "/sms", icon: MessageSquare, labelKey: "sms" },
  { to: "/branches", icon: Building2, labelKey: "branches", adminOnly: true },
  { to: "/wallet-management", icon: Wallet, labelKey: "walletManagement", adminOnly: true },
  { to: "/withdrawals", icon: Wallet, labelKey: "withdrawals" },
  { to: "/portal-access", icon: Wallet, labelKey: "portalAccess", adminOnly: true },
  { to: "/commission-settings", icon: Wallet, labelKey: "commissionSettings", adminOnly: true },
  
  { to: "/referral-mappings", icon: Users, labelKey: "referralMappings", adminOnly: true },
  { to: "/referral-lookup", icon: Users, labelKey: "referralLookup", adminOnly: true },
  {
    icon: BarChart3,
    labelKey: "reports",
    requiredPermissions: ["view_reports"],
    children: [
      { to: "/reports", labelKey: "reportsOverview" },
      { to: "/wallet-report", labelKey: "walletReport" },
      { to: "/branch-reports", labelKey: "branchReports" },
      { to: "/damage-report", labelKey: "damageReport" },
      { to: "/profit-loss", labelKey: "profitLoss" },
    ],
  },
  { to: "/backups", icon: DatabaseBackup, labelKey: "backup", adminOnly: true },
  { to: "/admin", icon: ShieldCheck, labelKey: "adminPanel", adminOnly: true },
  { to: "/settings", icon: Settings, labelKey: "settings" },
  
];

export function AppSidebar() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, signOut } = useAuth();
  const { lang, toggleLang, tr } = useLanguage();
  const { isAdmin, hasAnyPermission } = usePermissions();
  const [expanded, setExpanded] = useState<string[]>([]);

  // Filter nav items based on permissions
  const visibleItems = navItems.filter((item) => {
    if (item.adminOnly && !isAdmin) return false;
    if (item.requiredPermissions && !isAdmin && !hasAnyPermission(item.requiredPermissions)) return false;
    return true;
  });

  const toggleExpand = (key: string) => {
    setExpanded((prev) =>
      prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
    );
  };

  const handleLogout = async () => {
    // Log logout backup event
    if (user?.id) {
      const now = new Date();
      const fileName = `backup_logout_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}_${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}.zip`;
      const { error } = await supabase.from("backups").insert({
        type: "logout",
        file_name: fileName,
        size_bytes: 0,
        status: "completed",
        tables_included: ["all"],
        created_by: user.id,
      });

      if (error) {
        console.warn("Logout backup log skipped:", error.message);
      }
    }

    await signOut();
    toast.success(tr("logoutSuccess"));
    navigate({ to: "/login" });
  };

  const isActive = (to: string) =>
    to === "/" ? location.pathname === "/" : location.pathname.startsWith(to);

  return (
    <aside className="fixed left-0 top-0 z-40 flex h-screen w-60 flex-col bg-sidebar-bg text-sidebar-foreground">
      {/* Logo */}
      <div className="flex items-center gap-3 border-b border-sidebar-border px-5 py-4">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white overflow-hidden">
          <CompanyLogo className="h-full w-full object-contain" />
        </div>
        <div>
          <h1 className="text-sm font-bold text-sidebar-primary-foreground">NIYAMAH</h1>
          <p className="text-[10px] text-sidebar-foreground/60">Electric & Hardware</p>
        </div>
      </div>

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto px-3 py-3 space-y-0.5">
        {visibleItems.map((item) => {
          const hasChildren = item.children && item.children.length > 0;
          const isExpanded = expanded.includes(item.labelKey);
          const Icon = item.icon;

          if (hasChildren) {
            const childActive = item.children!.some((c) => isActive(c.to));
            return (
              <div key={item.labelKey}>
                <button
                  onClick={() => toggleExpand(item.labelKey)}
                  className={`flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                    childActive || isExpanded
                      ? "bg-sidebar-accent text-sidebar-primary"
                      : "text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
                  }`}
                >
                  <Icon className="h-4 w-4" />
                  <span className="flex-1 text-left">{tr(item.labelKey)}</span>
                  {isExpanded ? (
                    <ChevronDown className="h-3.5 w-3.5" />
                  ) : (
                    <ChevronRight className="h-3.5 w-3.5" />
                  )}
                </button>
                {isExpanded && (
                  <div className="ml-4 mt-0.5 space-y-0.5 border-l border-sidebar-border pl-3">
                    {item.children!.map((child) => (
                      <Link
                        key={child.to}
                        to={child.to}
                        className={`flex items-center gap-2 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${
                          isActive(child.to)
                            ? "text-sidebar-primary"
                            : "text-sidebar-foreground/60 hover:text-sidebar-foreground"
                        }`}
                      >
                        <span className="h-1 w-1 rounded-full bg-current" />
                        {tr(child.labelKey)}
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            );
          }

          if (!item.to) {
            return (
              <button
                key={item.labelKey}
                onClick={() => toggleExpand(item.labelKey)}
                className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground transition-colors"
              >
                <Icon className="h-4 w-4" />
                <span className="flex-1 text-left">{tr(item.labelKey)}</span>
                <ChevronRight className="h-3.5 w-3.5" />
              </button>
            );
          }

          return (
            <Link
              key={item.to}
              to={item.to}
              className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                isActive(item.to)
                  ? "bg-sidebar-accent text-sidebar-primary"
                  : "text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
              }`}
            >
              <Icon className="h-4 w-4" />
              {tr(item.labelKey)}
            </Link>
          );
        })}
      </nav>

      {/* Footer */}
      <div className="border-t border-sidebar-border px-3 py-3 space-y-0.5">
        <button
          onClick={toggleLang}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-sidebar-foreground/60 transition-colors hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
        >
          <Languages className="h-4 w-4" />
          {lang === "bn" ? "English" : "বাংলা"}
        </button>
        <button
          onClick={handleLogout}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm text-sidebar-foreground/60 transition-colors hover:bg-sidebar-accent/50 hover:text-sidebar-foreground"
        >
          <LogOut className="h-4 w-4" />
          {tr("logout")}
        </button>
      </div>
    </aside>
  );
}
