// File: src/components/UIX/SearchFilter/SearchFilter.jsx

import React, { memo, useMemo, useCallback, useEffect } from "react";
import {
  MagnifyingGlassIcon,
  FunnelIcon,
  XMarkIcon,
  ArrowPathIcon,
} from "@heroicons/react/24/outline";
import { ChevronDownIcon } from "@heroicons/react/20/solid";
import { useUIXTheme } from "../themes/useUIXTheme.jsx";

// Move static default values outside component to prevent recreation
const DEFAULT_SEARCH_PLACEHOLDER = "Search...";
const DEFAULT_STATUS_OPTIONS = [
  { value: "", label: "All Statuses" },
  { value: "1", label: "Active" },
  { value: "2", label: "Inactive" },
];
const DEFAULT_SORT_OPTIONS = [
  { value: "name,ASC", label: "Name (A-Z)" },
  { value: "name,DESC", label: "Name (Z-A)" },
  { value: "created_at,DESC", label: "Created Date (Newest)" },
  { value: "created_at,ASC", label: "Created Date (Oldest)" },
];
const DEFAULT_PAGE_SIZE_OPTIONS = [10, 25, 50, 100];

/**
 * SearchFilter Component - Performance Optimized
 * Reusable search and filter widget for list pages
 *
 * Performance optimizations:
 * - Component memoization with React.memo
 * - Static default values moved outside component
 * - Memoized theme classes to prevent multiple getThemeClasses calls
 * - Memoized className strings to prevent re-concatenation
 * - Optimized event handlers with useCallback
 * - Memoized sections (header, search input, filters, selects)
 * - Prevented unnecessary re-renders
 *
 * @param {string} searchTerm - Current search term
 * @param {string} tempSearchTerm - Temporary search term (for input)
 * @param {function} onSearchTermChange - Handler for search term changes
 * @param {function} onSearch - Handler for search submission
 * @param {string} searchPlaceholder - Placeholder text for search input
 * @param {Array} statusOptions - Array of {value, label} for status filter
 * @param {string} statusFilter - Current status filter value
 * @param {function} onStatusFilterChange - Handler for status filter changes
 * @param {Array} typeOptions - Array of {value, label} for type filter (optional)
 * @param {string} typeFilter - Current type filter value (optional)
 * @param {function} onTypeFilterChange - Handler for type filter changes (optional)
 * @param {string} typeFilterLabel - Label for the type filter (default: "Type")
 * @param {Array} sortOptions - Array of {value, label} for sort options
 * @param {string} sortValue - Current sort value (field,order)
 * @param {function} onSortChange - Handler for sort changes
 * @param {Array} pageSizeOptions - Array of page size values
 * @param {number} pageSize - Current page size
 * @param {function} onPageSizeChange - Handler for page size changes
 * @param {function} onClearFilters - Handler for clearing all filters
 * @param {function} onRefresh - Handler for refresh action
 * @param {string} className - Additional CSS classes
 */
const SearchFilter = memo(function SearchFilter({
  searchTerm,
  tempSearchTerm,
  onSearchTermChange,
  onSearch,
  searchPlaceholder = DEFAULT_SEARCH_PLACEHOLDER,
  statusOptions = DEFAULT_STATUS_OPTIONS,
  statusFilter,
  onStatusFilterChange,
  typeOptions,
  typeFilter,
  onTypeFilterChange,
  typeFilterLabel = "Type",
  sortOptions = DEFAULT_SORT_OPTIONS,
  sortValue,
  onSortChange,
  pageSizeOptions = DEFAULT_PAGE_SIZE_OPTIONS,
  pageSize,
  onPageSizeChange,
  onClearFilters,
  onRefresh,
  className = "",
}) {
  const { getThemeClasses } = useUIXTheme();

  // Memoize all theme classes to prevent multiple calls on each render
  const themeClasses = useMemo(
    () => ({
      searchBg: getThemeClasses('search-bg'),
      borderSecondary: getThemeClasses('border-secondary'),
      textPrimary: getThemeClasses('text-primary'),
      textMuted: getThemeClasses('text-muted'),
      textSecondary: getThemeClasses('text-secondary'),
      searchClearButton: getThemeClasses('search-clear-button'),
      searchRefreshButton: getThemeClasses('search-refresh-button'),
      inputBorder: getThemeClasses('input-border'),
      inputBg: getThemeClasses('input-bg'),
      focusRing: getThemeClasses('focus-ring'),
    }),
    [getThemeClasses],
  );

  // Memoize event handlers to prevent unnecessary re-renders
  const handleKeyPress = useCallback(
    (e) => {
      if (e.key === "Enter" && onSearch) {
        e.preventDefault();
        onSearch();
      }
    },
    [onSearch],
  );

  const handleSearchTermChange = useCallback(
    (e) => {
      if (onSearchTermChange) {
        onSearchTermChange(e.target.value);
      }
    },
    [onSearchTermChange],
  );

  const handleStatusChange = useCallback(
    (e) => {
      if (onStatusFilterChange) {
        onStatusFilterChange(e.target.value);
      }
    },
    [onStatusFilterChange],
  );

  const handleTypeChange = useCallback(
    (e) => {
      if (onTypeFilterChange) {
        onTypeFilterChange(e.target.value);
      }
    },
    [onTypeFilterChange],
  );

  const handleSortChange = useCallback(
    (e) => {
      if (onSortChange) {
        onSortChange(e.target.value);
      }
    },
    [onSortChange],
  );

  const handlePageSizeChange = useCallback(
    (e) => {
      const newValue = Number(e.target.value);
      if (onPageSizeChange) {
        onPageSizeChange(newValue);
      }
    },
    [onPageSizeChange],
  );

  // Memoize all className strings
  const containerClassName = useMemo(() => {
    return className
      ? `px-6 py-4 ${themeClasses.searchBg} border-b ${themeClasses.borderSecondary} ${className}`
      : `px-6 py-4 ${themeClasses.searchBg} border-b ${themeClasses.borderSecondary}`;
  }, [className, themeClasses.searchBg, themeClasses.borderSecondary]);

  const headerTitleClassName = useMemo(() => {
    return `text-sm font-medium ${themeClasses.textPrimary} flex items-center`;
  }, [themeClasses.textPrimary]);

  const headerIconClassName = useMemo(() => {
    return `w-4 h-4 mr-2 ${themeClasses.textMuted}`;
  }, [themeClasses.textMuted]);

  const clearButtonClassName = useMemo(() => {
    return `text-sm font-medium flex items-center transition-colors duration-200 ${themeClasses.searchClearButton}`;
  }, [themeClasses.searchClearButton]);

  const refreshButtonClassName = useMemo(() => {
    return `text-sm font-medium flex items-center transition-colors duration-200 ${themeClasses.searchRefreshButton}`;
  }, [themeClasses.searchRefreshButton]);

  const gridClassName = useMemo(() => {
    return typeOptions && typeOptions.length > 0
      ? 'grid grid-cols-1 gap-4 md:grid-cols-5'
      : 'grid grid-cols-1 gap-4 md:grid-cols-4';
  }, [typeOptions]);

  const labelClassName = useMemo(() => {
    return `block text-sm font-medium ${themeClasses.textPrimary} mb-1`;
  }, [themeClasses.textPrimary]);

  const inputClassName = useMemo(() => {
    return `w-full px-3 py-2 pr-10 border rounded-lg transition-all duration-200 ${themeClasses.inputBorder} ${themeClasses.inputBg} focus:outline-none focus:ring-2 ${themeClasses.focusRing}`;
  }, [themeClasses.inputBorder, themeClasses.inputBg, themeClasses.focusRing]);

  const selectClassName = useMemo(() => {
    return `w-full px-3 py-2 pr-10 border rounded-lg appearance-none transition-all duration-200 ${themeClasses.inputBorder} ${themeClasses.inputBg} focus:outline-none focus:ring-2 ${themeClasses.focusRing}`;
  }, [themeClasses.inputBorder, themeClasses.inputBg, themeClasses.focusRing]);

  const searchButtonClassName = useMemo(() => {
    return `absolute right-2 top-1/2 -translate-y-1/2 p-1 ${themeClasses.textMuted} hover:${themeClasses.textSecondary} transition-colors duration-200`;
  }, [themeClasses.textMuted, themeClasses.textSecondary]);

  const chevronClassName = useMemo(() => {
    return `absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 ${themeClasses.textMuted} pointer-events-none`;
  }, [themeClasses.textMuted]);

  // Memoize status options rendering
  const statusOptionsElements = useMemo(() => {
    return statusOptions.map((option, index) => (
      <option key={`status-${index}`} value={option.value}>
        {option.label}
      </option>
    ));
  }, [statusOptions]);

  // Memoize type options rendering
  const typeOptionsElements = useMemo(() => {
    if (!typeOptions) return null;
    return typeOptions.map((option, index) => (
      <option key={`type-${index}`} value={option.value}>
        {option.label}
      </option>
    ));
  }, [typeOptions]);

  // Memoize sort options rendering
  const sortOptionsElements = useMemo(() => {
    return sortOptions.map((option, index) => (
      <option key={`sort-${index}`} value={option.value}>
        {option.label}
      </option>
    ));
  }, [sortOptions]);

  // Memoize page size options rendering
  const pageSizeOptionsElements = useMemo(() => {
    return pageSizeOptions.map((size, index) => (
      <option key={`pagesize-${index}`} value={size.value || size}>
        {size.label || size}
      </option>
    ));
  }, [pageSizeOptions]);

  return (
    <div className={containerClassName}>
      {/* Header with title and actions */}
      <div className="flex items-center justify-between mb-4">
        <h3 className={headerTitleClassName}>
          <FunnelIcon className={headerIconClassName} />
          Filter & Search
        </h3>
        <div className="flex items-center gap-2">
          {onClearFilters && (
            <button
              onClick={onClearFilters}
              className={clearButtonClassName}
              aria-label="Clear all filters"
              title="Clear all filters"
            >
              <XMarkIcon className="w-4 h-4 mr-1" />
              Clear Filters
            </button>
          )}
          {onRefresh && (
            <button
              onClick={onRefresh}
              className={refreshButtonClassName}
              aria-label="Refresh data"
              title="Refresh data"
            >
              <ArrowPathIcon className="w-4 h-4 mr-1" />
              Refresh
            </button>
          )}
        </div>
      </div>

      {/* Filter Controls Grid */}
      <div className={gridClassName}>
        {/* Search Input */}
        <div>
          <label htmlFor="search-filter-input" className={labelClassName}>
            Search
          </label>
          <div className="relative">
            <input
              id="search-filter-input"
              name="search"
              type="text"
              value={tempSearchTerm}
              onChange={handleSearchTermChange}
              placeholder={searchPlaceholder}
              className={inputClassName}
              onKeyPress={handleKeyPress}
            />
            <button
              onClick={onSearch}
              className={searchButtonClassName}
              aria-label="Search"
              title="Search"
            >
              <MagnifyingGlassIcon className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Status Filter */}
        <div>
          <label htmlFor="search-filter-status" className={labelClassName}>
            Status
          </label>
          <div className="relative">
            <select
              id="search-filter-status"
              name="status"
              value={statusFilter}
              onChange={handleStatusChange}
              className={selectClassName}
            >
              {statusOptionsElements}
            </select>
            <ChevronDownIcon className={chevronClassName} />
          </div>
        </div>

        {/* Type Filter (optional) */}
        {typeOptions && typeOptions.length > 0 && (
          <div>
            <label htmlFor="search-filter-type" className={labelClassName}>
              {typeFilterLabel}
            </label>
            <div className="relative">
              <select
                id="search-filter-type"
                name="type"
                value={typeFilter}
                onChange={handleTypeChange}
                className={selectClassName}
              >
                {typeOptionsElements}
              </select>
              <ChevronDownIcon className={chevronClassName} />
            </div>
          </div>
        )}

        {/* Sort Options */}
        <div>
          <label htmlFor="search-filter-sort" className={labelClassName}>
            Sort By
          </label>
          <div className="relative">
            <select
              id="search-filter-sort"
              name="sort"
              value={sortValue}
              onChange={handleSortChange}
              className={selectClassName}
            >
              {sortOptionsElements}
            </select>
            <ChevronDownIcon className={chevronClassName} />
          </div>
        </div>

        {/* Items per page */}
        <div>
          <label htmlFor="search-filter-pagesize" className={labelClassName}>
            Items per page
          </label>
          <div className="relative">
            <select
              id="search-filter-pagesize"
              name="pageSize"
              value={pageSize}
              onChange={handlePageSizeChange}
              className={selectClassName}
            >
              {pageSizeOptionsElements}
            </select>
            <ChevronDownIcon className={chevronClassName} />
          </div>
        </div>
      </div>
    </div>
  );
});

// Set display name for React DevTools
SearchFilter.displayName = 'SearchFilter';

export default SearchFilter;