import { Button } from "@progress/kendo-react-buttons";
import { xIcon, searchIcon } from "@progress/kendo-svg-icons";
import {
  InputClearValue,
  InputSeparator,
  TextBox,
} from "@progress/kendo-react-inputs";
import { useEffect, useState } from "react";

const Prefix = ({ onClick }: any) => {
  return (
    <>
      <InputClearValue onClick={onClick}>
        <Button svgIcon={searchIcon} fillMode={"clear"} />
      </InputClearValue>
      <InputSeparator />
    </>
  );
};

const Suffix = ({ localSearch, onClick }: any) => {
  return localSearch ? (
    <>
      <InputSeparator />
      <InputClearValue
        onClick={() => {
          onClick({ target: { value: "" } });
        }}
      >
        <Button svgIcon={xIcon} fillMode={"clear"} />
      </InputClearValue>
    </>
  ) : (
    <></>
  );
};

const FilterCell = (props: any) => {
  const [localSearch, setLocalSearch] = useState("");

  useEffect(() => {
    const search = props.columnSearchValues?.filters?.find(
      (f: any) => f.field === props.column?.field
    );
    if (search && localSearch !== search.value) {
      setLocalSearch(search.value);
    }
  }, [props.columnSearchValues]);

  const onChange = (e: any) => {
    setLocalSearch(e.target.value || "");

    if (!e.target.value) {
      props.onLocalSearchChange({
        name: props.column?.field,
        value: "",
      });
    }
  };

  const handleKeyUp = (e: any) => {
    if (e.key === "Enter" || e.code === "Enter") {
      props.onLocalSearchChange({
        name: props.column?.field,
        value: localSearch,
      });
    }
  };

  const onSearchClick = () => {
    props.onLocalSearchChange({
      name: props.column?.field,
      value: localSearch,
    });
  };

  return (
    <TextBox
      value={localSearch}
      rounded="small"
      fillMode="outline"
      placeholder="Type here to search . . ."
      onKeyUp={handleKeyUp}
      onChange={onChange}
      suffix={() => <Suffix localSearch={localSearch} onClick={onChange} />}
      prefix={() => <Prefix onClick={onSearchClick} />}
    />
  );
};

export default FilterCell;
