"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";

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-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 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 = "#357a3d";
            }
          }}
          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-white text-slate-700"
          )}
          style={showFilters ? {
            borderColor: PRIMARY_COLOR,
            backgroundColor: PRIMARY_COLOR,
          } : {
            borderColor: `${PRIMARY_COLOR}66`,
          }}
          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-slate-200 bg-white 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-slate-200 pt-4">
            <button
              onClick={onReset}
              disabled={loading}
              className="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 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 = "#357a3d";
                }
              }}
              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-slate-700">
          {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-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-[#428B4D]/15 transition-all duration-200 ease-in-out hover:border-[#428B4D]/60 "
          style={{
            "--focus-border": PRIMARY_COLOR,
            "--focus-ring": `${PRIMARY_COLOR}33`,
          } as CSSPropertiesWithVars}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.boxShadow = `0 0 0 1px ${PRIMARY_COLOR}15`;
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.boxShadow = "";
          }}
          onMouseEnter={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = `${PRIMARY_COLOR}99`;
            }
          }}
          onMouseLeave={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = "";
            }
          }}
        />
      </div>
    );
  }

  if (filter.type === "date") {
    return (
      <div>
        <label className="mb-2 block text-xs font-semibold text-slate-700">
          {filter.label}
        </label>
        <input
          type="date"
          value={(filter.value as string) || ""}
          onChange={(e) => filter.onChange(e.target.value)}
          className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-[#428B4D]/15 transition-all duration-200 ease-in-out hover:border-[#428B4D]/60 "
          style={{
            "--focus-border": PRIMARY_COLOR,
            "--focus-ring": `${PRIMARY_COLOR}33`,
          } as CSSPropertiesWithVars}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.boxShadow = `0 0 0 1px ${PRIMARY_COLOR}15`;
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.boxShadow = "";
          }}
          onMouseEnter={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = `${PRIMARY_COLOR}99`;
            }
          }}
          onMouseLeave={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = "";
            }
          }}
        />
      </div>
    );
  }

  if (filter.type === "select") {
    return (
      <div>
        <label className="mb-2 block text-xs font-semibold text-slate-700">
          {filter.label}
        </label>
        <select
          value={(filter.value as string) || ""}
          onChange={(e) => filter.onChange(e.target.value)}
          className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-[#428B4D]/15 transition-all duration-200 ease-in-out hover:border-[#428B4D]/60 "
          style={{
            "--focus-border": PRIMARY_COLOR,
            "--focus-ring": `${PRIMARY_COLOR}33`,
          } as CSSPropertiesWithVars}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = PRIMARY_COLOR;
            e.currentTarget.style.boxShadow = `0 0 0 1px ${PRIMARY_COLOR}15`;
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = "";
            e.currentTarget.style.boxShadow = "";
          }}
          onMouseEnter={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = `${PRIMARY_COLOR}99`;
            }
          }}
          onMouseLeave={(e) => {
            if (document.activeElement !== e.currentTarget) {
              e.currentTarget.style.borderColor = "";
            }
          }}
        >
          <option value="">{filter.placeholder || "Select..."}</option>
          {filter.options?.map((option) => (
            <option key={option.id} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </div>
    );
  }

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

        {isOpen && (
          <div className="absolute z-50 mt-1 w-full rounded-lg border border-slate-200 bg-white shadow-lg">
            {/* Search Input */}
            <div className="p-3 border-b border-slate-200">
              <div className="relative group">
                <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400 transition-colors duration-200 group-hover:text-[#428B4D]" />
                <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-slate-300 rounded-md focus:outline-none focus:ring-1 focus:ring-[#428B4D]/15 transition-all duration-200 ease-in-out hover:border-[#428B4D]/60 "
                  style={{
                    "--focus-border": PRIMARY_COLOR,
                    "--focus-ring": `${PRIMARY_COLOR}33`,
                  } as CSSPropertiesWithVars}
                  onFocus={(e) => {
                    e.currentTarget.style.borderColor = PRIMARY_COLOR;
                    e.currentTarget.style.boxShadow = `0 0 0 1px ${PRIMARY_COLOR}15`;
                  }}
                  onBlur={(e) => {
                    e.currentTarget.style.borderColor = "";
                    e.currentTarget.style.boxShadow = "";
                  }}
                  onMouseEnter={(e) => {
                    if (document.activeElement !== e.currentTarget) {
                      e.currentTarget.style.borderColor = `${PRIMARY_COLOR}99`;
                    }
                  }}
                  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 = `${PRIMARY_COLOR}CC`;
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = PRIMARY_COLOR;
                    }}
                  >
                    Select All
                  </button>
                  <span className="text-slate-400">|</span>
                  <button
                    type="button"
                    onClick={handleClearAll}
                    className="hover:underline font-semibold"
                    style={{ color: PRIMARY_COLOR }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.color = `${PRIMARY_COLOR}CC`;
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.color = PRIMARY_COLOR;
                    }}
                  >
                    Clear All
                  </button>
                </div>
                {Array.isArray(filter.value) && (
                  <div className="text-slate-600 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-slate-500">
                  {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-slate-50 cursor-pointer rounded-lg transition-colors"
                  >
                    <input
                      type="checkbox"
                      checked={isSelected(option.value)}
                      onChange={() => handleToggle(option.value)}
                      className="h-4 w-4 rounded border-slate-300 cursor-pointer"
                      style={{
                        accentColor: "#ffd294",
                      }}
                    />
                    <span className="text-sm text-slate-700 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-slate-700">
          {filter.label}
        </label>
        <div className="max-h-32 overflow-y-auto rounded-lg border border-slate-300 bg-white p-2">
          {filter.options?.map((option) => (
            <label
              key={option.id}
              className="flex items-center gap-2 py-1 text-sm hover:bg-slate-50 px-2 rounded cursor-pointer"
            >
              <input
                type="checkbox"
                checked={isSelected(option.value)}
                onChange={() => handleToggle(option.value)}
                className="rounded border-slate-300 text-[#ffd294] focus:ring-[#ffd294]"
              />
              <span className="text-slate-900">{option.label}</span>
            </label>
          ))}
        </div>
      </div>
    );
  }

  return null;
}
