import { memo } from "preact/compat";
import { useRef } from "preact/hooks";
import { twMerge } from "tailwind-merge";

import Cancel from "../../icons/Cancel";
import Search from "../../icons/Search";
import useI18n from "../../utils/hooks/useI18n";
import IconButton from "../IconButton";
import Input from "../Input";

import type { PreactDOMAttributes } from "preact";
import type { HTMLAttributes, ReactNode } from "preact/compat";

import type { IconButtonProps } from "../IconButton/IconButton";
import type { InputProps } from "../Input/Input";

export type InputSearchProps = {
  cancelButtonClassName?: string;
  cancelButtonProps?: IconButtonProps;
  cancelIcon?: ReactNode;
  className?: string;
  inputClassName?: string;
  inputContainerClassName?: string;
  inputProps?: InputProps;
  resultClassName?: string;
  resultsClassName?: string;
  resultsContainerClassName?: string;
  searchIcon?: ReactNode;
  searchIconContainerClassName?: string;
  withResultsClassName?: string;
} & HTMLAttributes<HTMLDivElement> &
  PreactDOMAttributes;

/**
 * Rich search input component.
 */
function InputSearch({
  cancelButtonClassName,
  cancelButtonProps,
  cancelIcon,
  children,
  className,
  inputClassName,
  inputContainerClassName,
  inputProps,
  searchIcon,
  searchIconContainerClassName,
  withResultsClassName,
}: InputSearchProps) {
  const { t } = useI18n();
  const myRef = useRef<HTMLDivElement>();

  return (
    <>
      <div
        className={twMerge(
          "flex h-12 items-center gap-1 rounded-md bg-white p-3 shadow",
          className,
          withResultsClassName,
        )}
        ref={myRef}
      >
        <div
          className={twMerge(
            "text-grey flex items-center",
            searchIconContainerClassName,
          )}
        >
          {searchIcon || <Search />}
        </div>
        <div
          className={twMerge(
            "@container/inputsearch relative flex grow items-center gap-2 border-b-2 border-solid",
            inputContainerClassName,
          )}
        >
          <Input
            autoComplete="off"
            className={twMerge(
              "h-8 w-1 grow overflow-hidden text-ellipsis placeholder:text-zinc-400",
              inputClassName,
              inputProps?.value ? "pr-4" : "",
            )}
            type="text"
            {...(inputProps || {})}
          />
          {!!inputProps.value && (
            <IconButton
              className={twMerge(
                "absolute right-0 flex h-full w-6 items-center rounded-none border-none bg-transparent p-0 px-1 shadow-none",
                cancelButtonClassName,
              )}
              title={t("search_input_cancel")}
              {...(cancelButtonProps || {})}
            >
              {cancelIcon || <Cancel />}
            </IconButton>
          )}
        </div>
      </div>
      {children}
    </>
  );
}

export default memo(InputSearch);
