import React, { useRef } from "react";
import SearchIcon from "./icons/SearchIcon";
import CloseIcon from "./icons/CloseIcon";
import Button from "./Button";
import clsx from "clsx";

function SearchInput(
  props: React.InputHTMLAttributes<HTMLInputElement> & {
    onEnter?: () => void;
    setSearch: React.Dispatch<React.SetStateAction<string | null>>;
  }
) {
  const ref = useRef<HTMLInputElement>(null);

  return (
    <div
      className={clsx(
        "p-[0.556vw] bg-[#F6F6F6] rounded-[0.833vw] w-full flex items-center gap-[1.111vw] hover:bg-[#F0F0F0]",
        !props.onEnter && "px-[1.111vw] py-[1.215vw]"
      )}
    >
      <div className="flex gap-[0.566vw] items-center flex-1">
        <span className="text-[#7D7D7D] size-[1.389vw]">
          <SearchIcon />
        </span>
        <input
          className="outline-none focus:outline-none placeholder:button-m placeholder:font-medium placeholder:text-[#7D7D7D] button-m font-medium flex-1"
          {...props}
          ref={ref}
          onKeyDown={(e) => {
            if (e.key === "Enter") props.onEnter?.();
          }}
        />
      </div>
      <div
        className={clsx(
          "flex gap-[0.566vw] items-center transition-opacity",
          !props.value && "opacity-0"
        )}
      >
        <button
          disabled={!props.value}
          className="outline-none cursor-pointer disabled:cursor-default"
          // onClick={() => {
          //   if (ref.current) {
          //     ref.current.value = "";
          //     ref.current.focus();
          //   }
          // }}
        >
          <div
            className="text-[#7D7D7D] size-[1.111vw]"
            onClick={() => {
              if (ref.current) {
                ref.current.value = "";
                ref.current.focus();
                props.setSearch(ref.current.value);
              }
            }}
          >
            <CloseIcon />
          </div>
        </button>
        {props.onEnter && (
          <Button size="small" disabled={!props.value} onClick={props.onEnter}>
            Искать
          </Button>
        )}
      </div>
    </div>
  );
}

export default SearchInput;
