import * as React from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { X, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Skeleton } from "@/components/ui/skeleton";
import {
  ProductFilterOptions,
  ProductMetricColumnKey,
  ComparisonOperator,
  ActiveFilterValue,
  FilterValue,
} from "@/types/products";

// Define operators for different filter types
const STRING_OPERATORS: ComparisonOperator[] = ["contains", "equals", "starts_with", "ends_with", "not_contains", "is_empty", "is_not_empty"];
const NUMBER_OPERATORS: ComparisonOperator[] = ["=", ">", ">=", "<", "<=", "between", "is_empty", "is_not_empty"];
const BOOLEAN_OPERATORS: ComparisonOperator[] = ["is_true", "is_false"];
const DATE_OPERATORS: ComparisonOperator[] = ["=", ">", ">=", "<", "<=", "between", "is_empty", "is_not_empty"];
// Select filters use direct value selection (no operator UI), so only equality is applied
const SELECT_OPERATORS: ComparisonOperator[] = ["="];

interface FilterOption {
  id: ProductMetricColumnKey | 'search';
  label: string;
  type: "select" | "number" | "boolean" | "text" | "date" | "string";
  options?: { label: string; value: string }[];
  group: string;
  operators?: ComparisonOperator[];
}

interface ActiveFilterDisplay {
  id: string;
  label: string;
  value: ActiveFilterValue;
  displayValue: string;
}

// Base filter options available to users
const BASE_FILTER_OPTIONS: FilterOption[] = [
  // Basic Info group
  { id: 'sku', label: 'SKU', type: 'text', group: 'Basic Info', operators: STRING_OPERATORS },
  { id: 'title', label: 'Name', type: 'text', group: 'Basic Info', operators: STRING_OPERATORS },
  { id: 'barcode', label: 'UPC', type: 'text', group: 'Basic Info', operators: STRING_OPERATORS },
  { id: 'vendor', label: 'Supplier', type: 'select', group: 'Basic Info', operators: SELECT_OPERATORS, options: [] },
  { id: 'brand', label: 'Company', type: 'select', group: 'Basic Info', operators: SELECT_OPERATORS, options: [] },
  { id: 'line', label: 'Line', type: 'text', group: 'Basic Info', operators: STRING_OPERATORS },
  { id: 'subline', label: 'Subline', type: 'text', group: 'Basic Info', operators: STRING_OPERATORS },
  { id: 'artist', label: 'Artist', type: 'text', group: 'Basic Info', operators: STRING_OPERATORS },
  { id: 'isVisible', label: 'Visible', type: 'boolean', group: 'Basic Info', operators: BOOLEAN_OPERATORS },
  { id: 'isReplenishable', label: 'Replenishable', type: 'boolean', group: 'Basic Info', operators: BOOLEAN_OPERATORS },
  { id: 'abcClass', label: 'ABC Class', type: 'select', group: 'Basic Info', operators: SELECT_OPERATORS, options: [] },
  { id: 'status', label: 'Status', type: 'select', group: 'Basic Info', operators: SELECT_OPERATORS, options: [
    { value: 'Critical', label: 'Critical' },
    { value: 'At Risk', label: 'At Risk' },
    { value: 'Reorder Soon', label: 'Reorder Soon' },
    { value: 'Overstock', label: 'Overstock' },
    { value: 'Healthy', label: 'Healthy' },
    { value: 'New', label: 'New' },
  ]},
  { id: 'dateCreated', label: 'Created Date', type: 'date', group: 'Basic Info', operators: DATE_OPERATORS },
  
  // Supply Chain group
  { id: 'vendorReference', label: 'Supplier #', type: 'text', group: 'Supply Chain', operators: STRING_OPERATORS },
  { id: 'notionsReference', label: 'Notions #', type: 'text', group: 'Supply Chain', operators: STRING_OPERATORS },
  { id: 'harmonizedTariffCode', label: 'Tariff Code', type: 'text', group: 'Supply Chain', operators: STRING_OPERATORS },
  { id: 'countryOfOrigin', label: 'Country of Origin', type: 'text', group: 'Supply Chain', operators: STRING_OPERATORS },
  { id: 'location', label: 'Location', type: 'text', group: 'Supply Chain', operators: STRING_OPERATORS },
  { id: 'moq', label: 'MOQ', type: 'number', group: 'Supply Chain', operators: NUMBER_OPERATORS },
  
  // Physical Properties group
  { id: 'weight', label: 'Weight', type: 'number', group: 'Physical', operators: NUMBER_OPERATORS },
  { id: 'length', label: 'Length', type: 'number', group: 'Physical', operators: NUMBER_OPERATORS },
  { id: 'width', label: 'Width', type: 'number', group: 'Physical', operators: NUMBER_OPERATORS },
  { id: 'height', label: 'Height', type: 'number', group: 'Physical', operators: NUMBER_OPERATORS },
  { id: 'dimensions', label: 'Dimensions', type: 'text', group: 'Physical', operators: STRING_OPERATORS },
  
  // Customer Engagement group
  { id: 'rating', label: 'Rating', type: 'number', group: 'Customer', operators: NUMBER_OPERATORS },
  { id: 'reviews', label: 'Reviews Count', type: 'number', group: 'Customer', operators: NUMBER_OPERATORS },
  { id: 'baskets', label: 'Basket Adds', type: 'number', group: 'Customer', operators: NUMBER_OPERATORS },
  { id: 'notifies', label: 'Stock Alerts', type: 'number', group: 'Customer', operators: NUMBER_OPERATORS },
  
  // Inventory & Stock group
  { id: 'currentStock', label: 'Current Stock', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'preorderCount', label: 'Preorders', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'notionsInvCount', label: 'Notions Inventory', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'onOrderQty', label: 'On Order', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'configSafetyStock', label: 'Safety Stock', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'replenishmentUnits', label: 'Replenish Qty', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'toOrderUnits', label: 'To Order', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'stockCoverInDays', label: 'Stock Cover (Days)', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'sellsOutInDays', label: 'Sells Out In (Days)', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'isOldStock', label: 'Old Stock', type: 'boolean', group: 'Inventory', operators: BOOLEAN_OPERATORS },
  { id: 'overstockedUnits', label: 'Overstock Qty', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'stockoutDays30d', label: 'Stockout Days (30d)', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'stockoutRate30d', label: 'Stockout Rate %', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'avgStockUnits30d', label: 'Avg Stock Units (30d)', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'receivedQty30d', label: 'Received Qty (30d)', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'poCoverInDays', label: 'PO Cover (Days)', type: 'number', group: 'Inventory', operators: NUMBER_OPERATORS },
  { id: 'earliestExpectedDate', label: 'Expected Date', type: 'date', group: 'Inventory', operators: DATE_OPERATORS },
  
  // Pricing Group
  { id: "currentPrice", label: "Current Price", type: "number", group: "Pricing", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "currentRegularPrice", label: "Regular Price", type: "number", group: "Pricing", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "currentCostPrice", label: "Cost Price", type: "number", group: "Pricing", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Valuation Group
  { id: "currentStockCost", label: "Current Stock Cost", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "currentStockRetail", label: "Current Stock Retail", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "currentStockGross", label: "Current Stock Gross", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgStockCost30d", label: "Avg Stock Cost (30d)", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgStockRetail30d", label: "Avg Stock Retail (30d)", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgStockGross30d", label: "Avg Stock Gross (30d)", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "receivedCost30d", label: "Received Cost (30d)", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "replenishmentCost", label: "Replenishment Cost", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "replenishmentRetail", label: "Replenishment Retail", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "replenishmentProfit", label: "Replenishment Profit", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "onOrderCost", label: "On Order Cost", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "onOrderRetail", label: "On Order Retail", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "overstockedCost", label: "Overstock Cost", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "overstockedRetail", label: "Overstock Retail", type: "number", group: "Valuation", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Sales Metrics Group
  { id: "salesVelocityDaily", label: "Daily Velocity", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "yesterdaySales", label: "Yesterday Sales", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "sales7d", label: "Sales (7d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "revenue7d", label: "Revenue (7d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "sales14d", label: "Sales (14d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "revenue14d", label: "Revenue (14d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "sales30d", label: "Sales (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "revenue30d", label: "Revenue (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "sales365d", label: "Sales (365d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "revenue365d", label: "Revenue (365d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "dateLastSold", label: "Date Last Sold", type: "date", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgSalesPerDay30d", label: "Avg Sales/Day (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgSalesPerMonth30d", label: "Avg Sales/Month (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "returnsUnits30d", label: "Returns Units (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "returnsRevenue30d", label: "Returns Revenue (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "discounts30d", label: "Discounts (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "grossRevenue30d", label: "Gross Revenue (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "grossRegularRevenue30d", label: "Gross Regular Revenue (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "asp30d", label: "ASP (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "acp30d", label: "ACP (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgRos30d", label: "Avg ROS (30d)", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "lifetimeSales", label: "Lifetime Sales", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "lifetimeRevenue", label: "Lifetime Revenue", type: "number", group: "Sales Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // First Period Group
  { id: "first7DaysSales", label: "First 7 Days Sales", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first7DaysRevenue", label: "First 7 Days Revenue", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first30DaysSales", label: "First 30 Days Sales", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first30DaysRevenue", label: "First 30 Days Revenue", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first60DaysSales", label: "First 60 Days Sales", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first60DaysRevenue", label: "First 60 Days Revenue", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first90DaysSales", label: "First 90 Days Sales", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "first90DaysRevenue", label: "First 90 Days Revenue", type: "number", group: "First Period", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Financial KPIs
  { id: "cogs30d", label: "COGS (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "profit30d", label: "Profit (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "margin30d", label: "Margin % (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "markup30d", label: "Markup % (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "gmroi30d", label: "GMROI (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "stockturn30d", label: "Stock Turn (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "sellThrough30d", label: "Sell Thru % (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "returnRate30d", label: "Return Rate % (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "discountRate30d", label: "Discount Rate % (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "markdown30d", label: "Markdown (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "markdownRate30d", label: "Markdown Rate % (30d)", type: "number", group: "Financial Metrics", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Forecasting Group
  { id: "leadTimeForecastUnits", label: "Lead Time Forecast Units", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "daysOfStockForecastUnits", label: "Days of Stock Forecast Units", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "planningPeriodForecastUnits", label: "Planning Period Forecast Units", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "leadTimeClosingStock", label: "Lead Time Closing Stock", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "daysOfStockClosingStock", label: "Days of Stock Closing Stock", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "replenishmentNeededRaw", label: "Replenishment Needed Raw", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "forecastLostSalesUnits", label: "Forecast Lost Sales Units", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "forecastLostRevenue", label: "Forecast Lost Revenue", type: "number", group: "Forecasting", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Dates & Timing Group
  { id: "dateFirstReceived", label: "First Received", type: "date", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "dateLastReceived", label: "Last Received", type: "date", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "dateFirstSold", label: "First Sold", type: "date", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "ageDays", label: "Age (Days)", type: "number", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "avgLeadTimeDays", label: "Avg Lead Time", type: "number", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "replenishDate", label: "Replenish Date", type: "date", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "planningPeriodDays", label: "Planning Period (Days)", type: "number", group: "Dates", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Lead Time & Replenishment
  { id: "configLeadTime", label: "Config Lead Time", type: "number", group: "Lead Time", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "configDaysOfStock", label: "Config Days of Stock", type: "number", group: "Lead Time", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Growth Analysis Group
  { id: "salesGrowth30dVsPrev", label: "Sales Growth % (30d vs Prev)", type: "number", group: "Growth Analysis", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "revenueGrowth30dVsPrev", label: "Revenue Growth % (30d vs Prev)", type: "number", group: "Growth Analysis", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "salesGrowthYoy", label: "Sales Growth % YoY", type: "number", group: "Growth Analysis", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "revenueGrowthYoy", label: "Revenue Growth % YoY", type: "number", group: "Growth Analysis", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Demand Variability Group
  { id: "salesVariance30d", label: "Sales Variance (30d)", type: "number", group: "Demand Variability", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "salesStdDev30d", label: "Sales Std Dev (30d)", type: "number", group: "Demand Variability", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "salesCv30d", label: "Sales CV % (30d)", type: "number", group: "Demand Variability", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "demandPattern", label: "Demand Pattern", type: "text", group: "Demand Variability", operators: STRING_OPERATORS },
  
  // Service Level Group
  { id: "fillRate30d", label: "Fill Rate % (30d)", type: "number", group: "Service Level", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "stockoutIncidents30d", label: "Stockout Incidents (30d)", type: "number", group: "Service Level", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "serviceLevel30d", label: "Service Level % (30d)", type: "number", group: "Service Level", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "lostSalesIncidents30d", label: "Lost Sales Incidents (30d)", type: "number", group: "Service Level", operators: ["=", ">", ">=", "<", "<=", "between"] },
  
  // Seasonality Group
  { id: "seasonalityIndex", label: "Seasonality Index", type: "number", group: "Seasonality", operators: ["=", ">", ">=", "<", "<=", "between"] },
  { id: "seasonalPattern", label: "Seasonal Pattern", type: "text", group: "Seasonality", operators: STRING_OPERATORS },
  { id: "peakSeason", label: "Peak Season", type: "text", group: "Seasonality", operators: STRING_OPERATORS },
  
  // Data Quality Group
  { id: "lifetimeRevenueQuality", label: "Lifetime Revenue Quality", type: "text", group: "Data Quality", operators: STRING_OPERATORS },
];

interface ProductFiltersProps {
  filterOptions: ProductFilterOptions;
  isLoadingOptions: boolean;
  onFilterChange: (filters: Record<string, ActiveFilterValue>) => void;
  onClearFilters: () => void;
  activeFilters: Record<string, ActiveFilterValue>;
}

export function ProductFilters({
  filterOptions,
  isLoadingOptions,
  onFilterChange,
  onClearFilters,
  activeFilters,
}: ProductFiltersProps) {
  const [showCommand, setShowCommand] = React.useState(false);
  const [selectedFilter, setSelectedFilter] = React.useState<FilterOption | null>(null);
  const [selectedOperator, setSelectedOperator] = React.useState<ComparisonOperator>("=");
  const [inputValue, setInputValue] = React.useState("");
  const [inputValue2, setInputValue2] = React.useState(""); // For 'between' operator
  const [searchValue, setSearchValue] = React.useState("");

  const numberInputRef = React.useRef<HTMLInputElement>(null);
  const selectInputRef = React.useRef<HTMLInputElement>(null);
  const textInputRef = React.useRef<HTMLInputElement>(null);
  const dateInputRef = React.useRef<HTMLInputElement>(null);

  const handlePopoverClose = () => {
    setShowCommand(false);
    setSelectedFilter(null);
    setSelectedOperator("=");
    setInputValue("");
    setInputValue2("");
    setSearchValue("");
  };

  // Handle keyboard shortcuts
  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        setShowCommand(prev => !prev);
        if (showCommand) {
          handlePopoverClose();
        }
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [showCommand]);

  // Update filter options with dynamic data from props
  const processedFilterOptions = React.useMemo(() => {
    // Create a safe version of filterOptions with defaults to prevent undefined errors
    const safeFilterOptions = {
      vendors: filterOptions?.vendors || [],
      brands: filterOptions?.brands || [],
      abcClasses: filterOptions?.abcClasses || []
    };
    
    return BASE_FILTER_OPTIONS.map((option) => {
      const newOption = { ...option }; // Create mutable copy
      if (option.id === "vendor" && option.type === "select") {
        newOption.options = safeFilterOptions.vendors.map((v) => ({ label: v, value: v }));
      } else if (option.id === "brand" && option.type === "select") {
        newOption.options = safeFilterOptions.brands.map((b) => ({ label: b, value: b }));
      } else if (option.id === "abcClass" && option.type === "select") {
        newOption.options = safeFilterOptions.abcClasses.map((abc) => ({ label: abc, value: abc }));
      }
      return newOption;
    });
  }, [filterOptions]);

  // Filter options based on search
  const filteredOptions = React.useMemo(() => {
    if (!searchValue) return processedFilterOptions;
    const search = searchValue.toLowerCase();
    return processedFilterOptions.filter(
      (option) =>
        option.label.toLowerCase().includes(search) ||
        option.group.toLowerCase().includes(search)
    );
  }, [processedFilterOptions, searchValue]);

  const handleSelectFilter = React.useCallback((filter: FilterOption) => {
    setSelectedFilter(filter);
    setInputValue("");
    setInputValue2("");
    // Set default operator if the filter type supports operators
    setSelectedOperator(filter.operators?.[0] || "=");

    // Focus the appropriate input after state updates
    requestAnimationFrame(() => {
      if (filter.type === "number") numberInputRef.current?.focus();
      else if (filter.type === "select") selectInputRef.current?.focus();
      else if (filter.type === "date") dateInputRef.current?.focus();
      else textInputRef.current?.focus();
    });
  }, []);

  const handleApplyFilter = () => {
    if (!selectedFilter) return;

    let valueToApply: FilterValue | [string, string]; // Use string for dates
    let requiresOperator = selectedFilter.type === 'number' || selectedFilter.type === 'date' || selectedFilter.type === 'text';

    if (selectedOperator === 'between') {
      if (!inputValue || !inputValue2) return; // Need both values
      valueToApply = [inputValue, inputValue2];
      requiresOperator = true; // Always requires operator for between
    } else if (selectedFilter.type === 'number') {
      const numVal = parseFloat(inputValue);
      if (isNaN(numVal)) return; // Invalid number
      valueToApply = numVal;
    } else if (selectedFilter.type === 'select') {
      valueToApply = inputValue; // Value set directly via CommandItem select
      requiresOperator = false; // Usually simple equality for selects
    } else { // Text or Date (not between)
      if (!inputValue.trim()) return;
      valueToApply = inputValue.trim();
    }

    let filterValue: ActiveFilterValue;

    if (requiresOperator) {
      filterValue = {
        value: valueToApply,
        operator: selectedOperator,
      };
    } else {
      filterValue = valueToApply as FilterValue;
    }

    onFilterChange({
      ...activeFilters,
      [selectedFilter.id]: filterValue,
    });

    handlePopoverClose();
  };

  // Specific handler for select options to bypass operator selection
  const handleApplySelectFilter = (value: string) => {
    if (!selectedFilter) return;
    onFilterChange({ ...activeFilters, [selectedFilter.id]: value });
    handlePopoverClose();
  };

  const handleBackToFilters = () => {
    setSelectedFilter(null);
    setSelectedOperator("=");
    setInputValue("");
    setInputValue2("");
  };

  // Get display value for filter badges
  const getFilterDisplayValue = (id: string, value: ActiveFilterValue): string => {
    const option = processedFilterOptions.find(opt => opt.id === id);
    if (!option) return String(value); // Fallback

    if (typeof value === 'object' && value !== null && 'operator' in value) {
      // Boolean operators get friendly display
      if (value.operator === 'is_true') return `${option.label}: Yes`;
      if (value.operator === 'is_false') return `${option.label}: No`;
      if (value.operator === 'is_empty') return `${option.label}: is empty`;
      if (value.operator === 'is_not_empty') return `${option.label}: is not empty`;

      const opLabel = value.operator === '=' ? '' : `${value.operator} `;
      if (value.operator === 'between' && Array.isArray(value.value)) {
        return `${option.label}: ${value.value[0]} to ${value.value[1]}`;
      }
      return `${option.label}: ${opLabel}${value.value}`;
    }

    // Handle simple values (selects, booleans, text)
    if (option.type === 'select' || option.type === 'boolean') {
      const selectedOpt = option.options?.find(opt => opt.value === String(value));
      return `${option.label}: ${selectedOpt?.label || String(value)}`;
    }

    return `${option.label}: ${String(value)}`;
  };

  const activeFiltersList = React.useMemo((): ActiveFilterDisplay[] => {
    return Object.entries(activeFilters)
      .map(([id, value]): ActiveFilterDisplay => {
        const option = processedFilterOptions.find(opt => opt.id === id);

        return {
          id,
          label: option?.label || id,
          value,
          displayValue: getFilterDisplayValue(id, value),
        };
      })
      .filter((f): f is ActiveFilterDisplay => f !== null); // Type guard to remove nulls
  }, [activeFilters, processedFilterOptions]);

  // Render operator select
  const renderOperatorSelect = () => (
    <ToggleGroup
      type="single"
      value={selectedOperator}
      onValueChange={(value: ComparisonOperator) => value && setSelectedOperator(value)}
      className="flex-wrap justify-start gap-1"
      size="sm"
    >
      {selectedFilter?.operators?.map(op => (
        <ToggleGroupItem key={op} value={op} aria-label={op} className="px-2 py-1 h-7">
          {op === '=' ? '=' : op === '>=' ? '≥' : op === '<=' ? '≤' : op}
        </ToggleGroupItem>
      )) || (
        <ToggleGroupItem value="=" aria-label="equals" className="px-2 py-1 h-7">=</ToggleGroupItem>
      )}
    </ToggleGroup>
  );

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap items-center gap-2">
        <Popover open={showCommand} onOpenChange={setShowCommand} modal={true}>
          <PopoverTrigger asChild>
            <Button variant="outline" size="sm" className="h-8 border-dashed">
              <Plus className="mr-2 h-4 w-4"/> Add Filter
            </Button>
          </PopoverTrigger>
          <PopoverContent
            className="p-0 w-[520px]"
            align="start"
            onEscapeKeyDown={(event) => {
              if (selectedFilter) {
                event.preventDefault(); // Prevent popover closing
                handleBackToFilters();
              }
            }}
            onCloseAutoFocus={(e) => e.preventDefault()} // Prevent refocus on trigger
          >
            <Command className="rounded-none border-0" shouldFilter={false}>
              {!selectedFilter ? (
                <>
                  <CommandInput
                    placeholder="Search filters..."
                    value={searchValue}
                    onValueChange={setSearchValue}
                  />
                  <CommandList>
                    {isLoadingOptions ? (
                      <div className="p-4 space-y-2">
                        <Skeleton className="h-4 w-3/4" />
                        <Skeleton className="h-4 w-1/2" />
                        <Skeleton className="h-4 w-2/3" />
                      </div>
                    ) : (
                      <>
                        <CommandEmpty>No filters found.</CommandEmpty>
                        {Object.entries(
                          filteredOptions.reduce<Record<string, FilterOption[]>>(
                            (acc, filter) => {
                              if (!acc[filter.group]) acc[filter.group] = [];
                              acc[filter.group].push(filter);
                              return acc;
                            }, {}
                          )
                        ).map(([group, filtersInGroup]) => (
                          <CommandGroup key={group} heading={group}>
                            {filtersInGroup.map((filter) => (
                              <CommandItem
                                key={filter.id}
                                value={`${filter.id} ${filter.label}`}
                                onSelect={() => handleSelectFilter(filter)}
                                className={cn("cursor-pointer", activeFilters?.[filter.id] && "font-semibold")}
                              >
                                {filter.label}
                              </CommandItem>
                            ))}
                          </CommandGroup>
                        ))}
                      </>
                    )}
                  </CommandList>
                </>
              ) : (
                <div className="p-4 space-y-3">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={handleBackToFilters}
                    className="text-sm text-muted-foreground p-0 h-auto hover:bg-transparent"
                  >
                    ← {selectedFilter.label}
                  </Button>

                  {/* Render Operator Select for number, date, and text types */}
                  {(selectedFilter.type === 'number' || selectedFilter.type === 'date' || selectedFilter.type === 'text') && renderOperatorSelect()}

                  {/* Render Input based on type */}
                  <div className="flex items-center gap-2">
                    {selectedFilter.type === 'number' && (
                      <>
                        <Input
                          ref={numberInputRef}
                          type="number"
                          placeholder="Enter value"
                          value={inputValue}
                          onChange={(e) => setInputValue(e.target.value)}
                          onKeyDown={(e) => { if (e.key === 'Enter') handleApplyFilter(); }}
                          className="h-8 flex-1 min-w-0"
                        />
                        {selectedOperator === 'between' && (
                          <>
                            <span className="text-muted-foreground">and</span>
                            <Input
                              type="number"
                              placeholder="Enter max value"
                              value={inputValue2}
                              onChange={(e) => setInputValue2(e.target.value)}
                              onKeyDown={(e) => { if (e.key === 'Enter') handleApplyFilter(); }}
                              className="h-8 flex-1 min-w-0"
                            />
                          </>
                        )}
                      </>
                    )}
                    {selectedFilter.type === 'date' && (
                      <>
                        <Input
                          ref={dateInputRef}
                          type="date"
                          placeholder="YYYY-MM-DD"
                          value={inputValue}
                          onChange={(e) => setInputValue(e.target.value)}
                          onKeyDown={(e) => { if (e.key === 'Enter') handleApplyFilter(); }}
                          className="h-8 flex-1 min-w-0"
                        />
                        {selectedOperator === 'between' && (
                          <>
                            <span className="text-muted-foreground">and</span>
                            <Input
                              type="date"
                              placeholder="YYYY-MM-DD"
                              value={inputValue2}
                              onChange={(e) => setInputValue2(e.target.value)}
                              onKeyDown={(e) => { if (e.key === 'Enter') handleApplyFilter(); }}
                              className="h-8 flex-1 min-w-0"
                            />
                          </>
                        )}
                      </>
                    )}
                    {selectedFilter.type === 'text' && (
                      <Input
                        ref={textInputRef}
                        type="text"
                        placeholder={`Enter ${selectedFilter.label.toLowerCase()}`}
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        onKeyDown={(e) => { if (e.key === 'Enter') handleApplyFilter(); }}
                        className="h-8 flex-1"
                      />
                    )}

                    {/* Apply button for Number, Date, Text */}
                    {(selectedFilter.type === 'number' || selectedFilter.type === 'date' || selectedFilter.type === 'text') && (
                      <Button size="sm" onClick={handleApplyFilter} className="h-8">Apply</Button>
                    )}

                    {/* Select and Boolean types are handled via CommandList below */}
                  </div>

                  {/* Boolean type: show Yes/No buttons */}
                  {selectedFilter.type === 'boolean' && (
                    <div className="flex gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        className="flex-1 h-8"
                        onClick={() => {
                          onFilterChange({
                            ...activeFilters,
                            [selectedFilter.id]: { value: 'true', operator: 'is_true' as ComparisonOperator },
                          });
                          handlePopoverClose();
                        }}
                      >
                        Yes
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        className="flex-1 h-8"
                        onClick={() => {
                          onFilterChange({
                            ...activeFilters,
                            [selectedFilter.id]: { value: 'false', operator: 'is_false' as ComparisonOperator },
                          });
                          handlePopoverClose();
                        }}
                      >
                        No
                      </Button>
                    </div>
                  )}

                  {/* CommandList for Select type */}
                  {selectedFilter.type === 'select' && (
                    <Command className="mt-2 border rounded-md">
                      <CommandInput
                        ref={selectInputRef}
                        placeholder={`Search ${selectedFilter.label.toLowerCase()}...`}
                        value={inputValue}
                        onValueChange={setInputValue}
                      />
                      <CommandList>
                        <CommandEmpty>No options found.</CommandEmpty>
                        <CommandGroup>
                          {selectedFilter.options
                            ?.filter(option =>
                              option.label.toLowerCase().includes(inputValue.toLowerCase())
                            )
                            .map(option => (
                              <CommandItem
                                key={option.value}
                                value={option.value}
                                onSelect={() => handleApplySelectFilter(option.value)}
                                className="cursor-pointer"
                              >
                                {option.label}
                              </CommandItem>
                            ))}
                        </CommandGroup>
                      </CommandList>
                    </Command>
                  )}
                </div>
              )}
            </Command>
          </PopoverContent>
        </Popover>
        {activeFiltersList.map((filter) => (
          <Badge
            key={filter.id}
            variant="secondary"
            className="flex items-center gap-1 pl-2 pr-1 py-0.5"
          >
            <span className="text-xs">{filter.displayValue}</span>
            <Button
              variant="ghost"
              size="sm"
              className="h-4 w-4 p-0 ml-1 hover:bg-background rounded-full"
              onClick={() => {
                const { [filter.id]: _, ...rest } = activeFilters;
                onFilterChange(rest);
              }}
            >
              <X className="h-3 w-3" />
            </Button>
          </Badge>
        ))}
        {activeFiltersList.length > 0 && (
          <Button
            variant="ghost"
            size="sm"
            className="h-8 text-xs px-2"
            onClick={onClearFilters}
          >
            Clear All
          </Button>
        )}
      </div>
    </div>
  );
}
