"use client";

import { useState, useRef, useEffect } from "react";
import { Search, ChevronDown, X, Filter } from "lucide-react";
import { cn } from "@/lib/utils";
import { PRIMARY_COLOR, type CSSPropertiesWithVars } from "@/lib/common";
import DatePicker from "@/components/ui/DatePicker";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

/** Radix Select cannot hold "" — this stands in for "no filter applied". */
const REPORT_FILTER_NONE = "__none__";
export type FilterOption = {
  id: string;
  label: string;
  value: string;
};
export type FilterConfig = {
  type: "select" | "multi-select" | "search-multi-select" | "date" | "text";
  label: string;
  placeholder?: string;
  options?: FilterOption[];
  value?: string | string[];
  onChange: (value: any) => void;
};

export type ReportFiltersProps = {
  filters: FilterConfig[];
  onApply: () => void;
  onReset: () => void;
  loading?: boolean;
  showFilters?: boolean;
  onToggle?: () => void;
  variant?: "inline" | "panel";
  activeFilterCount?: number;
};

export function ReportFilters({
  filters,
  onApply,
  onReset,
  loading = false,
  showFilters = false,
  onToggle,
  variant = "panel",
  activeFilterCount = 0,
}: ReportFiltersProps) {

  const [searchTerms, setSearchTerms] = useState<Record<string, string>>({});
  if (variant === "inline") {
    return (
      <div className="flex items-center gap-2 flex-wrap">
        {filters.map((filter, index) => (
          <FilterField
            key={`${filter.label}-${index}`}
            filter={filter}
            searchTerm={searchTerms[filter.label] || ""}
            onSearchChange={(term) =>
              setSearchTerms({ ...searchTerms, [filter.label]: term })
            }
          />
        ))}
        <button
          onClick={onReset}
          disabled={loading}
          className="inline-flex items-center gap-1 rounded-lg border border-border-strong bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted transition-colors disabled:opacity-50"
        >
          <X size={14} />
          Reset
        </button>
        <button
          onClick={onApply}
          disabled={loading}
          className="inline-flex items-center gap-1 rounded-lg px-3 py-2 text-xs font-semibold text-white transition-colors disabled:opacity-50"
          style={{ backgroundColor: PRIMARY_COLOR }}
          onMouseEnter={(e) => {
            if (!e.currentTarget.disabled) {
              e.currentTarget.style.backgroundColor = "hsl(var(--primary-hover))";
            }
          }}
          onMouseLeave={(e) => {
            if (!e.currentTarget.disabled) {
              e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
            }
          }}
        >
          Apply
        </button>
      </div>
    );
  }

  return (
    <div>
      {onToggle && (
        <button
          onClick={onToggle}
          className={cn(
            "inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-semibold shadow-sm transition-all duration-200",
            showFilters
              ? "text-white"
              : "border-opacity-40 bg-card text-foreground"
          )}
          style={showFilters ? {
            borderColor: PRIMARY_COLOR,
            backgroundColor: PRIMARY_COLOR,
          } : {
            borderColor: `hsl(var(--primary) / 0.4)`,
          }}
          onMouseEnter={(e) => {
            if (!showFilters) {
              e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
              e.currentTarget.style.color = "white";
            }
          }}
          onMouseLeave={(e) => {
            if (!showFilters) {
              e.currentTarget.style.backgroundColor = "white";
              e.currentTarget.style.color = "";
            }
          }}
        >
          <Filter className="h-4 w-4" />
          Filters {activeFilterCount > 0 && `(${activeFilterCount})`}
        </button>
      )}

      {showFilters && (
        <div className="mt-6 rounded-lg border border-border bg-card p-4 shadow-sm">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filters.map((filter, index) => (
              <FilterField
                key={`${filter.label}-${index}`}
                filter={filter}
                searchTerm={searchTerms[filter.label] || ""}
                onSearchChange={(term) =>
                  setSearchTerms({ ...searchTerms, [filter.label]: term })
                }
              />
            ))}
          </div>

          <div className="mt-4 flex items-center gap-3 justify-end border-t border-border pt-4">
            <button
              onClick={onReset}
              disabled={loading}
              className="rounded-lg border border-border-strong bg-card px-4 py-2 text-sm font-semibold text-foreground hover:bg-muted transition-colors disabled:opacity-50"
            >
              Reset Filters
            </button>
            <button
              onClick={onApply}
              disabled={loading}
              className="rounded-lg px-4 py-2 text-sm font-semibold text-white transition-colors disabled:opacity-50"
              style={{ backgroundColor: PRIMARY_COLOR }}
              onMouseEnter={(e) => {
                if (!loading) {
                  e.currentTarget.style.backgroundColor = "hsl(var(--primary-hover))";
                }
              }}
              onMouseLeave={(e) => {
                if (!loading) {
                  e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
                }
              }}
            >
              {loading ? "Applying..." : "Apply Filters"}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function FilterField({
  filter,
  searchTerm,
  onSearchChange,
}: {
  filter: FilterConfig;
  searchTerm: string;
  onSearchChange: (term: string) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setIsOpen(false);
        onSearchChange(""); // Clear search when closing dropdown
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isOpen, onSearchChange]);

  // Check if search term contains comma delimiter
  const hasCommaDelimiter = searchTerm.includes(',');

  // Filter options based on search term with comma logic
  const filteredOptions = filter.options?.filter((option) => {
    if (!searchTerm) return true;

    if (hasCommaDelimiter) {
      // Split by comma and check if any term matches
      const terms = searchTerm.split(',').map(t => t.trim().toLowerCase()).filter(t => t);
      return terms.some(term =>
        term && option.label.toLowerCase().includes(term)
      );
    }

    return option.label.toLowerCase().includes(searchTerm.toLowerCase());
  }) || [];

  // Auto-clear and auto-select based on search term
  useEffect(() => {
    if (!Array.isArray(filter.value)) return;

    // When user starts typing, clear all selections first
    if (searchTerm.trim()) {
      if (hasCommaDelimiter && filteredOptions.length > 0) {
        // With comma delimiter: select only the matching items
        const matchedValues = filteredOptions.map(opt => opt.value);
        const currentValues = filter.value;

        // Only update if the selection is different
        const isDifferent =
          matchedValues.length !== currentValues.length ||
          matchedValues.some(val => !currentValues.includes(val)) ||
          currentValues.some(val => !matchedValues.includes(val));

        if (isDifferent) {
          filter.onChange(matchedValues);
        }
      } else {
        // Regular search without comma: clear all and select matching items
        const matchedValues = filteredOptions.map(opt => opt.value);
        const currentValues = filter.value;

        // Only update if the selection is different
        const isDifferent =
          matchedValues.length !== currentValues.length ||
          matchedValues.some(val => !currentValues.includes(val)) ||
          currentValues.some(val => !matchedValues.includes(val));

        if (isDifferent) {
          filter.onChange(matchedValues);
        }
      }
    }
  }, [searchTerm, hasCommaDelimiter, filteredOptions.length]);

  const getSelectedLabel = () => {
    if (!filter.value) return filter.placeholder || "Select...";

    if (Array.isArray(filter.value)) {
      const arrayValue = filter.value;
      const totalCount = filter.options?.length || 0;
      if (arrayValue.length === 0) return `0/${totalCount}`;
      if (arrayValue.length === 1) {
        const option = filter.options?.find(opt => opt.value === arrayValue[0]);
        return option?.label || arrayValue[0];
      }
      // Show count as "selected/total"
      return `${arrayValue.length}/${totalCount} selected`;
    }

    const option = filter.options?.find(opt => opt.value === filter.value);
    return option?.label || filter.value;
  };

  const isSelected = (value: string): boolean => {
    if (Array.isArray(filter.value)) {
      return filter.value.includes(value);
    }
    return filter.value === value;
  };

  const handleToggle = (value: string) => {
    if (Array.isArray(filter.value)) {
      const newValue = filter.value.includes(value)
        ? filter.value.filter(v => v !== value)
        : [...filter.value, value];
      filter.onChange(newValue);
    } else {
      filter.onChange(value);
      setIsOpen(false);
    }
  };

  const handleSelectAll = () => {
    if (filter.options) {
      filter.onChange(filter.options.map(opt => opt.value));
    }
  };

  const handleClearAll = () => {
    filter.onChange([]);
  };

  if (filter.type === "text") {
    return (
      <div>
        <label className="mb-2 block text-xs font-semibold text-foreground">
          {filter.label}
        </label>
        <input
          type="text"
          value={(filter.value as string) || ""}
          onChange={(e) => filter.onChange(e.target.value)}
          placeholder={filter.placeholder || "Enter value..."}
          className="w-full rounded-lg border border-border-strong bg-card px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary/15 transition-all duration-200 ease-in-out hover:border-primary/60 "
          style={{
            "--focus-border": PRIMARY_COLOR,
            "--focus-ring": `hsl(var(--primary) / 0.2)`,
          } as CSSPropertiesWithVars}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.boxShadow = `0 0 0 1px hsl(var(--primary) / 0.08)`;
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.boxShadow = "";
          }}
          onMouseEnter={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = `hsl(var(--primary) / 0.6)`;
            }
          }}
          onMouseLeave={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = "";
            }
          }}
        />
      </div>
    );
  }

  if (filter.type === "date") {

    return (
     <div className="relative z-50">
      <DatePicker
        label={filter.label}
        value={filter.value as string}
        onChange={(date) => {
          const formatted = date.toISOString().split("T")[0];
          filter.onChange(formatted);
        }}
      />
    </div>

    );
  }

  if (filter.type === "select") {
    return (
      <div>
        <label className="mb-2 block text-xs font-semibold text-foreground">
          {filter.label}
        </label>
        {/* Was a native <select> whose focus/hover border was driven by four
            inline React handlers writing style.borderColor. Radix renders the
            option list itself, so it follows the theme (a native list is drawn
            by the OS and would stay light in dark mode).

            Radix reserves "" as its no-selection sentinel, so the placeholder
            option uses a token that maps back to "" on change. */}
        <Select
          value={(filter.value as string) || REPORT_FILTER_NONE}
          onValueChange={(v) => filter.onChange(v === REPORT_FILTER_NONE ? "" : v)}
        >
          <SelectTrigger className="w-full" aria-label={filter.label}>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value={REPORT_FILTER_NONE}>
              {filter.placeholder || "Select…"}
            </SelectItem>
            {filter.options?.map((option) => (
              <SelectItem key={option.id} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    );
  }

  if (filter.type === "search-multi-select") {
    return (
      <div className="relative" ref={dropdownRef}>
        <label className="mb-2 block text-xs font-semibold text-foreground">
          {filter.label}
        </label>
        <button
          type="button"
          onClick={() => setIsOpen(!isOpen)}
          className="w-full rounded-lg border border-border-strong bg-card px-3 py-2 text-left text-sm focus:outline-none focus:ring-1 focus:ring-primary/15 transition-all duration-200 ease-in-out hover:border-primary/60  flex items-center justify-between"
          style={{
            "--focus-border": PRIMARY_COLOR,
            "--focus-ring": `hsl(var(--primary) / 0.2)`,
          } as CSSPropertiesWithVars}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.boxShadow = `0 0 0 1px hsl(var(--primary) / 0.08)`;
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.boxShadow = "";
          }}
          onMouseEnter={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = `hsl(var(--primary) / 0.6)`;
            }
          }}
          onMouseLeave={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = "";
            }
          }}
        >
          <span className={Array.isArray(filter.value) && filter.value.length === 0 ? "text-muted-foreground" : "text-foreground"}>
            {getSelectedLabel()}
          </span>
          <ChevronDown
            className={cn(
              "h-4 w-4 text-muted-foreground transition-transform",
              isOpen && "rotate-180"
            )}
          />
        </button>

        {isOpen && (
          <div className="absolute z-50 mt-1 w-full rounded-lg border border-border bg-card shadow-lg">
            {/* Search Input */}
            <div className="p-3 border-b border-border">
              <div className="relative group">
                <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground transition-colors duration-200 group-hover:text-primary" />
                <input
                  type="text"
                  placeholder="Search... (press tab or use comma to add multiple options)"
                  value={searchTerm}
                  onChange={(e) => onSearchChange(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Tab') {
                      e.preventDefault();
                      const input = e.currentTarget;
                      const cursorPos = input.selectionStart || 0;
                      const textBefore = searchTerm.slice(0, cursorPos);
                      const textAfter = searchTerm.slice(cursorPos);

                      // Add comma with space after if not already present
                      const newValue = textBefore + (textBefore.endsWith(',') || textBefore.endsWith(', ') ? ' ' : ', ') + textAfter;
                      onSearchChange(newValue);

                      // Set cursor position after the inserted comma and space
                      setTimeout(() => {
                        const newPos = textBefore.length + (textBefore.endsWith(',') || textBefore.endsWith(', ') ? 1 : 2);
                        input.setSelectionRange(newPos, newPos);
                      }, 0);
                    }
                  }}
                  className="w-full pl-8 pr-3 py-1.5 text-sm border border-border-strong rounded-md focus:outline-none focus:ring-1 focus:ring-primary/15 transition-all duration-200 ease-in-out hover:border-primary/60 "
                  style={{
                    "--focus-border": PRIMARY_COLOR,
                    "--focus-ring": `hsl(var(--primary) / 0.2)`,
                  } as CSSPropertiesWithVars}
                  onFocus={(e) => {
                    e.currentTarget.style.borderColor = PRIMARY_COLOR;
                    e.currentTarget.style.boxShadow = `0 0 0 1px hsl(var(--primary) / 0.08)`;
                  }}
                  onBlur={(e) => {
                    e.currentTarget.style.borderColor = "";
                    e.currentTarget.style.boxShadow = "";
                  }}
                  onMouseEnter={(e) => {
                    if (document.activeElement !== e.currentTarget) {
                      e.currentTarget.style.borderColor = `hsl(var(--primary) / 0.6)`;
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (document.activeElement !== e.currentTarget) {
                      e.currentTarget.style.borderColor = "";
                    }
                  }}
                  onClick={(e) => e.stopPropagation()}
                />
              </div>
              <div className="mt-2 flex items-center justify-between gap-2 text-xs">
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={handleSelectAll}
                    className="hover:underline font-semibold"
                    style={{ color: PRIMARY_COLOR }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = `hsl(var(--primary) / 0.8)`;
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = PRIMARY_COLOR;
                    }}
                  >
                    Select All
                  </button>
                  <span className="text-muted-foreground">|</span>
                  <button
                    type="button"
                    onClick={handleClearAll}
                    className="hover:underline font-semibold"
                    style={{ color: PRIMARY_COLOR }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = `hsl(var(--primary) / 0.8)`;
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = PRIMARY_COLOR;
                    }}
                  >
                    Clear All
                  </button>
                </div>
                {Array.isArray(filter.value) && (
                  <div className="text-muted-foreground font-semibold">
                    {filter.value.length}/{filter.options?.length || 0}
                  </div>
                )}
              </div>
            </div>

            {/* Options List */}
            <div className="max-h-60 overflow-y-auto p-2">
              {filteredOptions.length === 0 ? (
                <div className="px-3 py-4 text-center text-sm text-muted-foreground">
                  {searchTerm ? "No results found" : "No options available"}
                </div>
              ) : (
                filteredOptions.map((option) => (
                  <label
                    key={option.id}
                    className="flex items-center gap-3 px-3 py-2 hover:bg-muted cursor-pointer rounded-lg transition-colors"
                  >
                    {/* accentColor was #ffd294 — a pale peach that appears
                        nowhere else in the product. */}
                    <Checkbox
                      checked={isSelected(option.value)}
                      onCheckedChange={() => handleToggle(option.value)}
                    />
                    <span className="text-sm text-foreground flex-1">{option.label}</span>
                  </label>
                ))
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  if (filter.type === "multi-select") {
    return (
      <div>
        <label className="mb-2 block text-xs font-semibold text-foreground">
          {filter.label}
        </label>
        <div className="max-h-32 overflow-y-auto rounded-lg border border-border-strong bg-card p-2">
          {filter.options?.map((option) => (
            <label
              key={option.id}
              className="flex items-center gap-2 py-1 text-sm hover:bg-muted px-2 rounded cursor-pointer"
            >
              <Checkbox
                checked={isSelected(option.value)}
                onCheckedChange={() => handleToggle(option.value)}
              />
              <span className="text-foreground">{option.label}</span>
            </label>
          ))}
        </div>
      </div>
    );
  }

  return null;
}
