import {
  DropdownSearchInput,
  XButton,
} from "./SingleDropdown/SingleDropdown.styled";
import SearchIcon from "../../assets/svgs/search.svg";
import X from "../../assets/svgs/x.svg";
import { gray, primary } from "../../core/colors/colors";
import { useState } from "react";

export type DropdownSearchProps<T> = {
  value?: string;
  options: T[];
  optionLabel: (value: T) => string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onSearch: (filteredOptions: T[]) => void;
  filterValueClear: () => void;
  placeholder?: string;
};

const DropdownSearch = <T extends {}>({
  value,
  options,
  optionLabel,
  onChange,
  onSearch,
  filterValueClear,
  placeholder,
}: DropdownSearchProps<T>) => {
  const [isSearchFocus, setIsSearchFocus] = useState<boolean>(false);

  const onKeyDownEnterForSearch = (
    e: React.KeyboardEvent<HTMLInputElement>
  ) => {
    return options.filter((v) =>
      optionLabel(v)
        .replace(/\s| /gi, "")
        .toLowerCase()
        .includes(e.currentTarget.value.replace(/\s| /gi, "").toLowerCase())
    );
  };

  return (
    <DropdownSearchInput>
      <SearchIcon />
      <input
        className="dropdown_search_input"
        value={value}
        onFocus={() => setIsSearchFocus(true)}
        onBlur={() => setIsSearchFocus(false)}
        onChange={(e) => onChange(e)}
        onKeyDown={(e) =>
          e.key === "Enter" && onSearch(onKeyDownEnterForSearch(e))
        }
        placeholder={placeholder}
        style={{
          borderColor: isSearchFocus ? primary[500] : gray[300],
          paddingRight: value ? "40px" : "16px",
        }}
      />
      {value && (
        <XButton onClick={() => filterValueClear()}>
          <X />
        </XButton>
      )}
    </DropdownSearchInput>
  );
};

export default DropdownSearch;
