import { useState, useMemo, useCallback, useEffect } from "react";
import { apiFetch } from '@/utils/api';
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import config from "../config";
import { Skeleton } from "@/components/ui/skeleton"; // For loading states
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { ChevronDown, ChevronRight } from "lucide-react"; // Import icons for expand/collapse
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { Button } from "@/components/ui/button";

// Keep your existing type labels or fetch dynamically if preferred
const TYPE_LABELS: Record<number, string> = {
  10: "Section",
  11: "Category",
  12: "Subcategory",
  13: "Sub-Subcategory",
  1: "Company",
  2: "Line",
  3: "Subline",
  40: "Artist",
  20: "Theme",
  21: "Subtheme",
};

// Matches backend COLUMN_MAP keys for sorting
type CategorySortableColumns =
  | "categoryName"
  | "categoryType"
  | "parentName"
  | "productCount"
  | "activeProductCount"
  | "currentStockUnits"
  | "currentStockCost"
  | "currentStockRetail"
  | "revenue7d"
  | "revenue30d"
  | "profit30d"
  | "sales30d"
  | "avgMargin30d"
  | "stockTurn30d"
  | "salesGrowth30dVsPrev"
  | "revenueGrowth30dVsPrev"
  | "status";

interface CategoryMetric {
  // Assuming category_id is unique primary identifier in category_metrics
  category_id: string | number;
  category_name: string;
  category_type: number;
  parent_id: string | number | null;
  parent_name?: string | null; // Included conditionally by backend JOIN
  last_calculated: string;
  product_count: number;
  active_product_count: number;
  replenishable_product_count: number;
  current_stock_units: number;
  current_stock_cost: string | number;
  current_stock_retail: string | number;
  sales_7d: number;
  revenue_7d: string | number;
  sales_30d: number;
  revenue_30d: string | number;
  profit_30d: string | number;
  cogs_30d: string | number;
  sales_365d: number;
  revenue_365d: string | number;
  lifetime_sales: number;
  lifetime_revenue: string | number;
  avg_margin_30d: string | number | null;
  stock_turn_30d: string | number | null;
  // Growth metrics
  sales_growth_30d_vs_prev: string | number | null;
  revenue_growth_30d_vs_prev: string | number | null;
  // Fields from categories table
  status: string;
  description: string;
  // Camel case versions
  categoryId: string | number;
  categoryName: string;
  categoryType: number;
  parentId: string | number | null;
  parentName?: string | null;
  lastCalculated: string;
  productCount: number;
  activeProductCount: number;
  replenishableProductCount: number;
  currentStockUnits: number;
  currentStockCost: string | number;
  currentStockRetail: string | number;
  lifetimeSales: number;
  lifetimeRevenue: string | number;
  avgMargin_30d: string | number | null;
  stockTurn_30d: string | number | null;
  salesGrowth30dVsPrev: string | number | null;
  revenueGrowth30dVsPrev: string | number | null;
  direct_active_product_count: number;
  direct_current_stock_units: number;
  direct_stock_cost: string | number;
  direct_revenue_30d: string | number;
  direct_profit_30d: string | number;
}

// Define response type to avoid type errors
interface CategoryResponse {
  categories: CategoryMetric[];
  pagination: {
    total: number;
    pages: number;
    currentPage: number;
    limit: number;
  };
}

interface CategoryFilterOptions {
  types: { value: number; label: string }[];
  statuses: string[]; // Status filter from categories table
  typeCounts: { type: number; count: number }[]; // Type counts from categories.js
}

interface CategoryStats {
  totalCategories: number;
  activeCategories: number;
  totalActiveProducts: number;
  totalValue: number;
  avgMargin: number;
}

interface CategoryFilters {
  search: string;
  type: string; // Store type value as string for 'all' option
  status: string;
  showInactive: boolean; // Filter for showing categories with 0 active products
}

// Helper for formatting
const formatCurrency = (
  value: number | string | null | undefined,
  digits = 0
): string => {
  if (value == null) return "N/A";
  if (typeof value === "string") {
    const parsed = parseFloat(value);
    if (isNaN(parsed)) return "N/A";
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: digits,
      maximumFractionDigits: digits,
    }).format(parsed);
  }
  if (typeof value !== "number" || isNaN(value)) return "N/A";
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  }).format(value);
};

const formatNumber = (
  value: number | string | null | undefined,
  digits = 0
): string => {
  if (value == null) return "N/A";
  if (typeof value === "string") {
    const parsed = parseFloat(value);
    if (isNaN(parsed)) return "N/A";
    return parsed.toLocaleString(undefined, {
      minimumFractionDigits: digits,
      maximumFractionDigits: digits,
    });
  }
  if (typeof value !== "number" || isNaN(value)) return "N/A";
  return value.toLocaleString(undefined, {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  });
};

const formatPercentage = (
  value: number | string | null | undefined,
  digits = 1
): string => {
  if (value == null) return "N/A";
  if (typeof value === "string") {
    const parsed = parseFloat(value);
    if (isNaN(parsed)) return "N/A";
    return `${parsed.toFixed(digits)}%`;
  }
  if (typeof value !== "number" || isNaN(value)) return "N/A";
  return `${value.toFixed(digits)}%`;
};

// Growth formatting with color coding
const formatGrowth = (value: number | string | null | undefined, digits = 1) => {
  if (value == null) return <span className="text-muted-foreground">N/A</span>;
  
  const numValue = typeof value === "string" ? parseFloat(value) : value;
  if (isNaN(numValue)) return <span className="text-muted-foreground">N/A</span>;
  
  const formatted = `${numValue >= 0 ? '+' : ''}${numValue.toFixed(digits)}%`;
  const colorClass = numValue >= 0 ? 'text-green-600' : 'text-red-600';
  
  return <span className={colorClass}>{formatted}</span>;
};

// Define interfaces for hierarchical structure
interface CategoryWithChildren extends CategoryMetric {
  children: CategoryWithChildren[];
  hierarchyLevel?: number;
  isLast?: boolean;
  isExpanded?: boolean;
  aggregatedStats?: {
    activeProductCount: number;
    currentStockUnits: number;
    currentStockCost: number;
    revenue30d: number;
    profit30d: number;
    avg_margin_30d?: number;
    sales_growth_30d_vs_prev?: number;
    revenue_growth_30d_vs_prev?: number;
  };
}

// Add type-specific colors
const TYPE_COLORS: Record<number, string> = {
  10: "bg-blue-100 text-blue-800 hover:bg-blue-200", // Section
  11: "bg-blue-50 text-blue-700 hover:bg-blue-100", // Category
  12: "bg-blue-50/70 text-blue-600 hover:bg-blue-50", // Subcategory
  13: "bg-blue-50/50 text-blue-500 hover:bg-blue-50/70", // Sub-subcategory

  20: "bg-violet-100 text-violet-800 hover:bg-violet-200", // Theme
  21: "bg-violet-50 text-violet-700 hover:bg-violet-100", // Subtheme

  1: "bg-amber-100 text-amber-800 hover:bg-amber-200", // Company
  2: "bg-amber-50 text-amber-700 hover:bg-amber-100", // Line
  3: "bg-amber-50/70 text-amber-600 hover:bg-amber-50", // Subline

  40: "bg-emerald-100 text-emerald-800 hover:bg-emerald-200", // Artist
};

// TypeBadge component for consistent type display
const TypeBadge = ({
  type,
  className = "",
}: {
  type: number;
  className?: string;
}) => {
  const typeLabel = TYPE_LABELS[type] || `Type ${type}`;
  const colorClass =
    TYPE_COLORS[type] || "bg-gray-100 text-gray-800 hover:bg-gray-200";

  return (
    <Badge
      variant="outline"
      className={`${colorClass} ${className} w-[95px] justify-center`}
    >
      {typeLabel}
    </Badge>
  );
};

// Simplify the Categories component by removing the second query and data merging
export function Categories() {
  const [sortColumn, setSortColumn] =
    useState<CategorySortableColumns>("categoryName");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
  const [filters, setFilters] = useState<CategoryFilters>({
    search: "",
    type: "all",
    status: "all",
    showInactive: false, // Keep this true by default to show all categories
  });
  // Add state for expanded categories
  const [expandedCategories, setExpandedCategories] = useState<
    Set<string | number>
  >(new Set());

  // Sort indicator component - moved inside to access sortDirection
  const SortIndicator = ({ active }: { active: boolean }) => {
    if (!active) return null;
    return (
      <span className="ml-1 text-xs">
        {sortDirection === "asc" ? "▲" : "▼"}
      </span>
    );
  };

  // Toggle expand/collapse for a category
  const toggleExpand = (categoryId: string | number) => {
    setExpandedCategories((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(categoryId)) {
        newSet.delete(categoryId);
      } else {
        newSet.add(categoryId);
      }
      return newSet;
    });
  };

  // Expand all categories
  const expandAll = () => {
    if (hierarchicalCategories) {
      const allIds = new Set<string | number>();
      const collectIds = (categories: CategoryWithChildren[]) => {
        categories.forEach((cat) => {
          allIds.add(cat.category_id);
          if (cat.children.length > 0) {
            collectIds(cat.children);
          }
        });
      };
      collectIds(hierarchicalCategories);
      setExpandedCategories(allIds);
    }
  };

  // Collapse all categories
  const collapseAll = () => {
    setExpandedCategories(new Set());
  };

  // Update the query parameters to get all categories
  const queryParams = useMemo(() => {
    const params = new URLSearchParams();
    // Set high limit to get ALL categories
    params.set("limit", "5000");

    // Always send proper server-side sort parameters
    params.set("sort", sortColumn);
    params.set("order", sortDirection);

    // Only add search params if we're filtering
    if (filters.search) {
      params.set("categoryName_ilike", filters.search);
    }
    
    if (filters.type !== "all") {
      // The backend expects categoryType_eq
      // The type is stored as integer in the database
      console.log(`Setting categoryType_eq to: ${filters.type}`);
      params.set("categoryType_eq", filters.type);
    }
    
    if (filters.status !== "all") {
      params.set("status", filters.status);
    }
    
    // Only filter by active products if explicitly requested
    if (!filters.showInactive) {
      params.set("activeProductCount_gt", "0");
    }

    console.log("Filters:", filters);
    console.log("Query params:", params.toString());
    
    return params;
  }, [sortColumn, sortDirection, filters]);

  // Simplify to a single query
  const {
    data: listData,
    isLoading: isLoadingList,
    error: listError,
  } = useQuery<CategoryResponse, Error>({
    queryKey: ["categories-all", queryParams.toString()],
    queryFn: async () => {
      const url = `${config.apiUrl}/categories-aggregate?${queryParams.toString()}`;
      console.log("Fetching categories from URL:", url);
      
      const response = await apiFetch(url, {
        credentials: "include",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "Cache-Control": "no-cache",
        },
      });
      
      if (!response.ok) {
        throw new Error(`Network response was not ok (${response.status})`);
      }
      
      const data = await response.json();
      console.log(`Received ${data.categories.length} categories from API`);
      
      if (filters.type !== "all") {
        // Check if any categories match the filter
        const matchingCategories = data.categories.filter(
          (cat: CategoryMetric) => cat.category_type.toString() === filters.type
        );
        console.log(`Filter type=${filters.type}: ${matchingCategories.length} matching categories found`);
      }
      
      return data;
    },
    staleTime: 0,
  });

  const { data: statsData, isLoading: isLoadingStats } = useQuery<
    CategoryStats,
    Error
  >({
    queryKey: ["categoriesStats"],
    queryFn: async () => {
      const response = await apiFetch(
        `${config.apiUrl}/categories-aggregate/stats`,
        {
          credentials: "include",
        }
      );
      if (!response.ok) throw new Error("Failed to fetch category stats");
      return response.json();
    },
  });

  const { data: filterOptions } = useQuery<
    CategoryFilterOptions,
    Error
  >({
    queryKey: ["categoriesFilterOptions"],
    queryFn: async () => {
      const response = await apiFetch(
        `${config.apiUrl}/categories-aggregate/filter-options`,
        {
          credentials: "include",
        }
      );
      if (!response.ok)
        throw new Error("Failed to fetch category filter options");
      const data = await response.json();
      console.log("Filter options:", data);
      return data;
    },
  });

  // Simplify the categories derivation
  const categories = listData?.categories || [];

  // Update loading variables
  const isLoadingAll = isLoadingList;

  // Build the hierarchical tree structure
  const hierarchicalCategories = useMemo(() => {
    console.log(`Building hierarchical structure from ${categories.length} categories`);
    if (!categories || categories.length === 0) return [];
    
    // DIRECT CALCULATION: Create a map to directly calculate accurate totals
    // This approach doesn't rely on the tree structure for calculations
    const directTotalsMap = new Map<string | number, {
      revenue30d: number,
      profit30d: number,
      activeProductCount: number,
      currentStockUnits: number,
      currentStockCost: number
    }>();
    
    // First, identify all parent-child relationships
    const childToParentMap = new Map<string | number, string | number>();
    categories.forEach(cat => {
      if (cat.parent_id) {
        childToParentMap.set(cat.category_id, cat.parent_id);
      }
    });
    
    // For filtered results, we need a different approach to handle missing parents
    // If we've filtered by type, we might have categories without their parents in the results
    const isFiltered = filters.type !== 'all' || filters.search !== '';
    console.log(`isFiltered: ${isFiltered}, type: ${filters.type}, search: "${filters.search}"`);
    
    // Build sets of all descendants for each category
    const allDescendantsMap = new Map<string | number, Set<string | number>>();
    
    // Helper to get all descendants recursively
    const getAllDescendants = (categoryId: string | number): Set<string | number> => {
      if (allDescendantsMap.has(categoryId)) {
        return allDescendantsMap.get(categoryId)!;
      }
      
      const descendants = new Set<string | number>();
      
      // Find direct children
      categories.forEach(cat => {
        if (cat.parent_id === categoryId) {
          descendants.add(cat.category_id);
          // Add their descendants recursively
          const childDescendants = getAllDescendants(cat.category_id);
          childDescendants.forEach(id => descendants.add(id));
        }
      });
      
      // Cache and return
      allDescendantsMap.set(categoryId, descendants);
      return descendants;
    };
    
    // Calculate descendants for all categories
    categories.forEach(cat => {
      if (!allDescendantsMap.has(cat.category_id)) {
        getAllDescendants(cat.category_id);
      }
    });
    
    // Now use pre-calculated database values instead of calculating totals directly
    categories.forEach(cat => {
      // Use the pre-calculated values from the database
      const totalRevenue = parseFloat(cat.revenue_30d?.toString() || '0');
      const totalProfit = parseFloat(cat.profit_30d?.toString() || '0');
      const totalActiveProducts = cat.active_product_count || 0;
      const totalStockUnits = cat.current_stock_units || 0;
      const totalStockCost = parseFloat(cat.current_stock_cost?.toString() || '0');
      
      // Set the pre-calculated totals
      directTotalsMap.set(cat.category_id, {
        revenue30d: totalRevenue,
        profit30d: totalProfit,
        activeProductCount: totalActiveProducts,
        currentStockUnits: totalStockUnits,
        currentStockCost: totalStockCost
      });
    });
    
    // First, create a lookup map by category ID
    const categoryMap = new Map<string | number, CategoryWithChildren>();
    categories.forEach((cat) => {
      categoryMap.set(cat.category_id, { ...cat, children: [] });
    });

    // When filtering by type, we need to change our approach - all categories should
    // be treated as root level categories since we explicitly want to see them
    if (isFiltered) {
      console.log(`Using flat structure for filtered results (${categories.length} items)`);
      // For filtered results, just show a flat list
      const filteredCategories = categories.map(cat => {
        const processedCat = categoryMap.get(cat.category_id);
        if (!processedCat) return null;
        
        // Give these categories a direct parent-child relationship based on parent_id
        // if the parent also exists in the filtered results
        if (cat.parent_id && categoryMap.has(cat.parent_id)) {
          const parent = categoryMap.get(cat.parent_id);
          if (parent) {
            parent.children.push(processedCat);
          }
        }
        
        return processedCat;
      }).filter(Boolean) as CategoryWithChildren[];
      
      // Only return top-level categories after creating parent-child relationships
      const rootFilteredCategories = filteredCategories.filter(cat => 
        !cat.parent_id || !categoryMap.has(cat.parent_id)
      );
      
      console.log(`Returning ${rootFilteredCategories.length} root filtered categories with type = ${filters.type}`);
      
      // Apply hierarchy levels
      const computeHierarchyAndLevels = (
        categories: CategoryWithChildren[],
        level = 0
      ) => {
        return categories.map((cat, index, arr) => {
          // Set hierarchy level
          cat.hierarchyLevel = level;
          cat.isLast = index === arr.length - 1;
          cat.isExpanded = expandedCategories.has(cat.category_id);

          // Process children to set their hierarchy levels
          if (cat.children.length > 0) {
            computeHierarchyAndLevels(cat.children, level + 1);
          }

          // Aggregated stats already set above
          return cat;
        });
      };
      
      return computeHierarchyAndLevels(rootFilteredCategories);
    }

    // Regular hierarchical structure for unfiltered results
    // Then organize into a hierarchical structure
    const rootCategories: CategoryWithChildren[] = [];

    // First pass: Add children to parents
    categories.forEach((cat) => {
      const processedCat = categoryMap.get(cat.category_id);
      if (!processedCat) return;

      if (cat.parent_id && categoryMap.has(cat.parent_id)) {
        // This is a child category, add to parent's children array
        const parent = categoryMap.get(cat.parent_id);
        if (parent) {
          parent.children.push(processedCat);
        }
      } else if (cat.parent_id) {
        // This is an orphaned category
      } else {
        // This is a root category
        rootCategories.push(processedCat);
      }
    });
    
    // Set hierarchy levels and use the direct aggregates we calculated
    const computeHierarchyAndLevels = (
      categories: CategoryWithChildren[],
      level = 0
    ) => {
      return categories.map((cat, index, arr) => {
        // Set hierarchy level
        cat.hierarchyLevel = level;
        cat.isLast = index === arr.length - 1;
        cat.isExpanded = expandedCategories.has(cat.category_id);

        // Process children to set their hierarchy levels
        if (cat.children.length > 0) {
          computeHierarchyAndLevels(cat.children, level + 1);
        }

        // Make sure we set aggregatedStats for ALL categories, not just those with children
        // First check if we have pre-calculated values
        const totals = directTotalsMap.get(cat.category_id);
        
        if (totals) {
          // Use our pre-calculated totals for all metrics
          cat.aggregatedStats = {
            activeProductCount: totals.activeProductCount,
            currentStockUnits: totals.currentStockUnits,
            currentStockCost: totals.currentStockCost,
            revenue30d: totals.revenue30d,
            profit30d: totals.profit30d,
            avg_margin_30d: totals.revenue30d > 0 
              ? (totals.profit30d / totals.revenue30d) * 100 
              : 0,
            sales_growth_30d_vs_prev: parseFloat(cat.sales_growth_30d_vs_prev?.toString() || "0"),
            revenue_growth_30d_vs_prev: parseFloat(cat.revenue_growth_30d_vs_prev?.toString() || "0")
          };
        } else {
          // If we don't have pre-calculated values (shouldn't happen with our algorithm)
          // Ensure every category still has aggregatedStats set with its direct values
          cat.aggregatedStats = {
            activeProductCount: cat.direct_active_product_count || 0,
            currentStockUnits: cat.direct_current_stock_units || 0,
            currentStockCost: parseFloat(cat.direct_stock_cost?.toString() || "0"),
            revenue30d: parseFloat(cat.direct_revenue_30d?.toString() || "0"),
            profit30d: parseFloat(cat.direct_profit_30d?.toString() || "0"),
            avg_margin_30d: parseFloat(cat.avg_margin_30d?.toString() || "0"),
            sales_growth_30d_vs_prev: parseFloat(cat.sales_growth_30d_vs_prev?.toString() || "0"),
            revenue_growth_30d_vs_prev: parseFloat(cat.revenue_growth_30d_vs_prev?.toString() || "0")
          };
        }

        return cat;
      });
    };

    // Apply hierarchy levels and use our pre-calculated totals
    const result = computeHierarchyAndLevels(rootCategories);
    console.log(`Returning ${result.length} hierarchical categories`);
    
    return result;
  }, [categories, expandedCategories, filters.type, filters.search]);

  // Check if there are no categories to display and explain why
  useEffect(() => {
    if (hierarchicalCategories.length === 0 && categories.length > 0) {
      console.log("Warning: No hierarchical categories to display even though API returned", categories.length, "categories");
      console.log("Filter settings:", filters);
    }
  }, [hierarchicalCategories, categories, filters]);

  // Recursive function to render category rows with streamlined stat display
  const renderCategoryRow = (
    category: CategoryWithChildren,
    isVisible: boolean = true
  ) => {
    // Get indentation level
    const hierarchyLevel = category.hierarchyLevel || 0;
    const indentPadding = `${hierarchyLevel * 1.5}rem`; // 24px per level

    // Determine if this category is expandable
    const hasChildren = category.children && category.children.length > 0;
    const isExpanded = expandedCategories.has(category.category_id);

    // Rows for this category and its children
    const rows = [];

    // Add this category's row if it should be visible
    if (isVisible) {
      rows.push(
        <TableRow
          key={category.category_id}
          // Add subtle hover effect and dim inactive/empty categories
          className={`${
            category.active_product_count === 0 ? "opacity-60" : ""
          } hover:bg-muted/50`}
        >
          {/* Name Cell (Includes hierarchy indicator and expand/collapse toggle) */}
          <TableCell className="h-16 py-2">
            <div
              className="flex items-center"
              style={{ paddingLeft: indentPadding }}
            >
              {hasChildren && (
                <Button // Use Button for better accessibility/styling
                  variant="ghost" // Use ghost variant for minimal styling
                  size="icon" // Use icon size
                  onClick={() => toggleExpand(category.category_id)}
                  className="mr-1 h-6 w-6 p-0" // Adjust size and padding
                >
                  {isExpanded ? (
                    <ChevronDown size={16} />
                  ) : (
                    <ChevronRight size={16} />
                  )}
                </Button>
              )}
              {/* Add a spacer for non-expandable items at deeper levels for alignment */}
              {!hasChildren && hierarchyLevel > 0 && (
                <span className="inline-block h-6 w-6 mr-1"></span>
              )}
              {/* If it's a top-level item without children, add a spacer only if needed */}
              {!hasChildren && hierarchyLevel === 0 && !hasChildren && (
                <span className="inline-block h-6 w-6 mr-1"></span>
              )}
              <span className="font-medium">{category.category_name}</span>
            </div>
          </TableCell>

          {/* Type Cell */}
          <TableCell className="h-16 py-2">
            <TypeBadge type={category.category_type} />
          </TableCell>

          {/* Parent Cell */}
          <TableCell className="h-16 py-2">
            {category.parent_name || "-"}
          </TableCell>

          {/* Active Products Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  {/* Show only aggregated value prominently */}
                  <span className="font-medium cursor-help">
                    {" "}
                    {/* Added cursor */}
                    {formatNumber(category.aggregatedStats.activeProductCount)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Total (incl. children):{" "}
                    {formatNumber(category.aggregatedStats.activeProductCount)}
                  </p>
                  <p>
                    Directly in '{category.category_name}':{" "}
                    {formatNumber(category.direct_active_product_count)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              // Leaf node or no aggregation needed, show direct value
              formatNumber(category.active_product_count)
            )}
          </TableCell>

          {/* Stock Units Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="font-medium cursor-help">
                    {formatNumber(category.aggregatedStats.currentStockUnits)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Total Units (incl. children):{" "}
                    {formatNumber(category.aggregatedStats.currentStockUnits)}
                  </p>
                  <p>
                    Directly in '{category.category_name}':{" "}
                    {formatNumber(category.direct_current_stock_units)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              formatNumber(category.current_stock_units)
            )}
          </TableCell>

          {/* Stock Value Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="font-medium cursor-help">
                    {formatCurrency(category.aggregatedStats.currentStockCost)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Total Value (incl. children):{" "}
                    {formatCurrency(category.aggregatedStats.currentStockCost)}
                  </p>
                  <p>
                    Directly in '{category.category_name}':{" "}
                    {formatCurrency(category.direct_stock_cost)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              formatCurrency(category.current_stock_cost)
            )}
          </TableCell>

          {/* Revenue (30d) Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="font-medium cursor-help">
                    {formatCurrency(category.aggregatedStats.revenue30d)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Total Revenue (incl. children):{" "}
                    {formatCurrency(category.aggregatedStats.revenue30d)}
                  </p>
                  <p>
                    Directly from '{category.category_name}':{" "}
                    {formatCurrency(category.direct_revenue_30d)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              formatCurrency(category.aggregatedStats ? category.aggregatedStats.revenue30d : category.revenue_30d)
            )}
          </TableCell>

          {/* Profit (30d) Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="font-medium cursor-help">
                    {formatCurrency(category.aggregatedStats.profit30d)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Total Profit (incl. children):{" "}
                    {formatCurrency(category.aggregatedStats.profit30d)}
                  </p>
                  <p>
                    Directly from '{category.category_name}':{" "}
                    {formatCurrency(category.direct_profit_30d)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              formatCurrency(category.aggregatedStats ? category.aggregatedStats.profit30d : category.profit_30d)
            )}
          </TableCell>

          {/* Margin (30d) Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats
              ? (() => {
                  // IIFE to calculate aggregated margin for display
                  const aggRevenue = category.aggregatedStats.revenue30d;
                  const aggProfit = category.aggregatedStats.profit30d;
                  // Handle division by zero or non-numeric inputs safely
                  const aggMargin =
                    typeof aggRevenue === "number" &&
                    aggRevenue > 0 &&
                    typeof aggProfit === "number"
                      ? (aggProfit / aggRevenue) * 100
                      : null; // Or 0 if preferred over N/A

                  return (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span className="font-medium cursor-help">
                          {formatPercentage(aggMargin)}
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>
                          Avg Margin (incl. children):{" "}
                          {formatPercentage(aggMargin)}
                        </p>
                        <p>
                          Directly from '{category.category_name}':{" "}
                          {formatPercentage(category.avg_margin_30d)}
                        </p>
                      </TooltipContent>
                    </Tooltip>
                  );
                })()
              : // Show direct margin for leaf nodes or non-aggregated rows
                formatPercentage(category.avg_margin_30d)}
          </TableCell>

          {/* Sales Growth Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="font-medium cursor-help">
                    {formatGrowth(category.aggregatedStats.sales_growth_30d_vs_prev)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Sales Growth (incl. children):{" "}
                    {formatGrowth(category.aggregatedStats.sales_growth_30d_vs_prev)}
                  </p>
                  <p>
                    Directly from '{category.category_name}':{" "}
                    {formatGrowth(category.sales_growth_30d_vs_prev)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              formatGrowth(category.sales_growth_30d_vs_prev)
            )}
          </TableCell>

          {/* Revenue Growth Cell */}
          <TableCell className="h-16 py-2 text-right">
            {hasChildren && category.aggregatedStats ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="font-medium cursor-help">
                    {formatGrowth(category.aggregatedStats.revenue_growth_30d_vs_prev)}
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  <p>
                    Revenue Growth (incl. children):{" "}
                    {formatGrowth(category.aggregatedStats.revenue_growth_30d_vs_prev)}
                  </p>
                  <p>
                    Directly from '{category.category_name}':{" "}
                    {formatGrowth(category.revenue_growth_30d_vs_prev)}
                  </p>
                </TooltipContent>
              </Tooltip>
            ) : (
              formatGrowth(category.revenue_growth_30d_vs_prev)
            )}
          </TableCell>

          {/* Stock Turn (30d) Cell - Display direct value */}
          <TableCell className="h-16 py-2 text-right">
            {formatNumber(category.stock_turn_30d, 2)}
          </TableCell>
        </TableRow>
      );
    }

    // Add child rows if this category is expanded and should be visible
    if (hasChildren && isExpanded) {
      category.children.forEach((child) => {
        // The visibility of children depends only on the parent being expanded
        // (The parent's visibility check is done above)
        rows.push(...renderCategoryRow(child, true));
      });
    }

    return rows;
  };

  // Move the renderGroupedCategories function inside the component body
  // where it has access to all required variables
  const renderGroupedCategories = () => {
    if (isLoadingAll) {
      return Array.from({ length: 10 }).map((_, i) => (
        <TableRow key={`skel-${i}`} className="h-16">
          <TableCell className="w-[25%]">
            <div className="flex items-center">
              <span className="inline-block h-6 w-6 mr-1"></span>
              <Skeleton className="h-5 w-40" />
            </div>
          </TableCell>
          <TableCell className="w-[95px]">
            <Skeleton className="h-5 w-full" />
          </TableCell>
          <TableCell className="w-[15%]">
            <Skeleton className="h-5 w-full" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[8%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
          <TableCell className="text-right w-[6%]">
            <Skeleton className="h-5 w-full ml-auto" />
          </TableCell>
        </TableRow>
      ));
    }

    console.log("Rendering categories:", {
      hierarchicalCategories: hierarchicalCategories?.length || 0,
      categories: categories?.length || 0,
      filters
    });

    if (!hierarchicalCategories || hierarchicalCategories.length === 0) {
      // Check hierarchicalCategories directly
      return (
        <TableRow>
          <TableCell
            colSpan={13}
            className="h-16 text-center py-8 text-muted-foreground"
          >
            {categories && categories.length > 0 ? (
              <>
                <p>We found {categories.length} matching categories but encountered an issue displaying them.</p>
                <p className="mt-2">Try adjusting your filter criteria or refreshing the page.</p>
              </>
            ) : (
              filters.search || filters.type !== "all" || !filters.showInactive
                ? "No categories found matching your criteria. Try adjusting filters."
                : "No categories available."
            )}
          </TableCell>
        </TableRow>
      );
    }

    // Directly render the hierarchical tree roots
    const rows = hierarchicalCategories
      .map((category) => renderCategoryRow(category))
      .flat();
    
    console.log(`Rendering ${rows.length} total rows`);
    return rows;
  };

  // --- Event Handlers ---

  const handleSort = useCallback(
    (column: CategorySortableColumns) => {
      setSortDirection((prev) => {
        if (sortColumn !== column) return "desc";
        return prev === "asc" ? "asc" : "desc";
      });
      setSortColumn(column);

      // Collapse all categories when changing sort to prevent confusion
      setExpandedCategories(new Set());
    },
    [sortColumn]
  );

  const handleFilterChange = useCallback(
    (filterName: keyof CategoryFilters, value: string | boolean) => {
      console.log(`Filter change: ${filterName} = ${value} (${typeof value})`);
      setFilters((prev) => ({ ...prev, [filterName]: value }));
      
      // Debug the type filter when changed
      if (filterName === 'type') {
        console.log(`Type filter changed to: ${value}`);
      }
    },
    []
  );

  // Log any error in category fetching
  useEffect(() => {
    if (listError) {
      console.error("Error fetching categories:", listError);
    }
  }, [listError]);

  // Log when filter options are received
  useEffect(() => {
    if (filterOptions) {
      console.log("Filter options loaded:", filterOptions);
      console.log("Available types:", filterOptions.types);
    }
  }, [filterOptions]);

  // --- Rendering ---

  return (
    <div className="container mx-auto py-6 space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold tracking-tight">Categories</h1>
        <div className="text-sm text-muted-foreground">
          {isLoadingAll
            ? "Loading..."
            : `${formatNumber(categories.length)} categories`}
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Total Categories
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoadingStats ? (
              <Skeleton className="h-8 w-24" />
            ) : (
              <div className="text-2xl font-bold">
                {formatNumber(statsData?.totalCategories)}
              </div>
            )}
            <p className="text-xs text-muted-foreground">
              {isLoadingStats ? (
                <Skeleton className="h-4 w-28" />
              ) : (
                `${formatNumber(statsData?.activeCategories)} active`
              )}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Total Stock Value
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoadingStats ? (
              <Skeleton className="h-8 w-28" />
            ) : (
              <div className="text-2xl font-bold">
                {formatCurrency(statsData?.totalValue)}
              </div>
            )}
            <p className="text-xs text-muted-foreground">Current cost value</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Avg Margin (30d)
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoadingStats ? (
              <Skeleton className="h-8 w-20" />
            ) : (
              <div className="text-2xl font-bold">
                {formatPercentage(statsData?.avgMargin)}
              </div>
            )}
            <p className="text-xs text-muted-foreground">Weighted by revenue</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">
              Total Active Products
            </CardTitle>
          </CardHeader>
          <CardContent>
            {isLoadingStats ? (
              <Skeleton className="h-8 w-24" />
            ) : (
              <div className="text-2xl font-bold">
                {formatNumber(statsData?.totalActiveProducts)}
              </div>
            )}
            <p className="text-xs text-muted-foreground">
              Across all categories
            </p>
          </CardContent>
        </Card>
        {/* Note: Avg Growth card removed as data is not available from the new /stats endpoint */}
      </div>

      {/* Filter Controls */}
      <div className="flex flex-wrap items-center gap-2">
        <div className="flex-1 flex flex-wrap gap-2">
          <Input
            placeholder="Search categories..."
            value={filters.search}
            onChange={(e) => handleFilterChange("search", e.target.value)}
            className="w-full sm:w-[250px]"
          />
          <Select
            value={filters.type}
            onValueChange={(value) => handleFilterChange("type", value)}
          >
            <SelectTrigger className="w-full sm:w-[180px]">
              <SelectValue placeholder="Category Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Types</SelectItem>
              {filterOptions?.types.map((type) => (
                <SelectItem key={type.value} value={type.value.toString()}>
                  {type.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <div className="flex items-center space-x-2">
            <Switch
              id="show-inactive-categories"
              checked={filters.showInactive}
              onCheckedChange={(checked) =>
                handleFilterChange("showInactive", checked)
              }
            />
            <Label htmlFor="show-inactive-categories">
              Show inactive/empty
            </Label>
          </div>
        </div>
        <div className="flex sm:flex-row flex-col items-center gap-2">
          <div className="flex items-center space-x-2">
            <Button
              variant="secondary"
              size="sm"
              onClick={expandAll}
              className=""
            >
              Expand All
            </Button>
            <Button
              variant="secondary"
              size="sm"
              onClick={collapseAll}
              className=""
            >
              Collapse All
            </Button>
          </div>
        </div>
      </div>

      {/* Data Table */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead
                onClick={() => handleSort("categoryName")}
                className="h-16 cursor-pointer w-[25%]"
              >
                Name
                <SortIndicator active={sortColumn === "categoryName"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("categoryType")}
                className="cursor-pointer w-[100px]"
              >
                Type
                <SortIndicator active={sortColumn === "categoryType"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("parentName")}
                className="cursor-pointer w-[15%]"
              >
                Parent
                <SortIndicator active={sortColumn === "parentName"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("activeProductCount")}
                className="cursor-pointer text-right w-[8%]"
              >
                Active Products
                <SortIndicator active={sortColumn === "activeProductCount"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("currentStockUnits")}
                className="cursor-pointer text-right w-[8%]"
              >
                Stock Units
                <SortIndicator active={sortColumn === "currentStockUnits"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("currentStockCost")}
                className="cursor-pointer text-right w-[8%]"
              >
                Stock Value
                <SortIndicator active={sortColumn === "currentStockCost"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("revenue30d")}
                className="cursor-pointer text-right w-[8%]"
              >
                Revenue (30d)
                <SortIndicator active={sortColumn === "revenue30d"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("profit30d")}
                className="cursor-pointer text-right w-[8%]"
              >
                Profit (30d)
                <SortIndicator active={sortColumn === "profit30d"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("avgMargin30d")}
                className="cursor-pointer text-right w-[8%]"
              >
                Margin (30d)
                <SortIndicator active={sortColumn === "avgMargin30d"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("salesGrowth30dVsPrev")}
                className="cursor-pointer text-right w-[8%]"
              >
                Sales Growth
                <SortIndicator active={sortColumn === "salesGrowth30dVsPrev"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("revenueGrowth30dVsPrev")}
                className="cursor-pointer text-right w-[8%]"
              >
                Revenue Growth
                <SortIndicator active={sortColumn === "revenueGrowth30dVsPrev"} />
              </TableHead>
              <TableHead
                onClick={() => handleSort("stockTurn30d")}
                className="cursor-pointer text-right w-[6%]"
              >
                Stock Turn (30d)
                <SortIndicator active={sortColumn === "stockTurn30d"} />
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>{renderGroupedCategories()}</TableBody>
        </Table>
      </div>
    </div>
  );
}

export default Categories;
