import React, { forwardRef, useEffect, useCallback } from "react";
import { Checkbox } from "../Checkbox";

const SearchFilter = forwardRef(
  (
    {
      isClearable,
      onSearch,
      isMulti,
      onSelectAll,
      onClearAll,
      isSelectAll,
      selectedOptions,
      toggleSelectAll,
      isWithSearch,
      onKeyDown,
      onSubmenuKeyDown,
      searchPlaceholder,
      isLoading,
      searchTerm,
      externalOnSearch,
      setSearchTerm,
      onSearchBlur,
      selectionLabels = {},
      onClose,
      setHighlightedIndex,
      setIsKeyboardNav,
      highlightedIndex = -1,
      isSelectAllHighlighted = false,
    },
    ref
  ) => {
    const hasSelectAll = isMulti && toggleSelectAll && !isLoading;

    useEffect(() => {
      setSearchTerm("");
    }, []);

    const handleSearchKeyDown = useCallback(
      (e) => {
        if (onSubmenuKeyDown?.(e)) return;

        if ((e.ctrlKey || e.metaKey) && e.key === "a" && isMulti) {
          e.preventDefault();
          if (onSelectAll) {
            const syntheticEvent = { target: { checked: !isSelectAll } };
            onSelectAll(syntheticEvent);
          }
          return;
        }

        const isOnOptions = highlightedIndex >= 0;
        const isOnSelectAll = highlightedIndex === -1 && hasSelectAll;

        switch (e.key) {
          case "ArrowDown": {
            e.preventDefault();
            setIsKeyboardNav?.(true);
            if (isOnOptions || isOnSelectAll) {
              onKeyDown?.(e);
            } else if (hasSelectAll) {
              setHighlightedIndex?.(-1);
            } else {
              setHighlightedIndex?.(0);
            }
            break;
          }
          case "ArrowUp": {
            e.preventDefault();
            if (isOnOptions || isOnSelectAll) {
              onKeyDown?.(e);
            }
            break;
          }
          case "Enter": {
            if (isOnOptions || isOnSelectAll) {
              e.preventDefault();
              onKeyDown?.(e);
            }
            break;
          }
          case " ": {
            if ((isOnOptions || isOnSelectAll) && !searchTerm) {
              e.preventDefault();
              onKeyDown?.(e);
            }
            break;
          }
          case "Home":
          case "End": {
            if (isOnOptions) {
              e.preventDefault();
              onKeyDown?.(e);
            }
            break;
          }
          case "Escape": {
            e.preventDefault();
            onClose?.();
            break;
          }
          case "Tab": {
            onClose?.();
            break;
          }
          default:
            break;
        }
      },
      [onKeyDown, onSubmenuKeyDown, onClose, setHighlightedIndex, setIsKeyboardNav, isMulti, onSelectAll, isSelectAll, hasSelectAll, highlightedIndex, searchTerm]
    );

    return (
      <>
        {isWithSearch && (
          <input
            className="ia-select-search-box"
            placeholder={searchPlaceholder}
            ref={ref}
            onChange={onSearch}
            onKeyDown={handleSearchKeyDown}
            value={searchTerm}
            onBlur={onSearchBlur}
            role="searchbox"
            aria-label={searchPlaceholder || "Search options"}
            autoComplete="off"
          />
        )}
        {hasSelectAll && (
          <div className="ia-select-search-container">
            <div
              className={`ia-select-selectAll-container${isSelectAllHighlighted ? " ia-select-option-highlighted" : ""}`}
              role="option"
              aria-selected={isSelectAll}
            >
              <Checkbox
                name="select-all"
                id="select-all"
                label={isSelectAll ? (selectionLabels.deselectAll || "Deselect All") : (selectionLabels.selectAll || "Select All")}
                onChange={onSelectAll}
                checked={isSelectAll}
                className="select-selectAll-checkbox"
              />
              {isClearable && selectedOptions.length > 0 && (
                <button
                  className="ia-select-clear-all-button"
                  variant="url"
                  aria-label="Clear all selections"
                  onClick={() => onClearAll()}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      e.preventDefault();
                      e.stopPropagation();
                      onClearAll();
                    }
                  }}
                >
                  Clear
                </button>
              )}
            </div>
          </div>
        )}
      </>
    );
  }
);

export default SearchFilter;
