import { ChangeEvent, ChangeEventHandler, RefObject } from "react";
import { twJoin } from "tailwind-merge";

import { InputButton } from "./InputButton";

export interface ClearButtonProps {
  hidden?: boolean;
  onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>;
  onClear?: () => void;
  inputRef?: RefObject<HTMLElement>;
}

export const ClearButton = ({
  onChange,
  inputRef,
  onClear,
  hidden = false,
}: ClearButtonProps) => {
  function handleClick() {
    onChange?.({
      target: { value: "" },
    } as ChangeEvent<HTMLInputElement | HTMLTextAreaElement>);

    onClear?.();
    if (inputRef?.current != null) {
      if ("value" in inputRef.current) {
        inputRef.current.value = "";
      }
      inputRef.current.focus();
    }
  }

  return (
    <div className="min-w-[20px]">
      <InputButton
        aria-label="Leegmaken"
        icon="xmark-circle-fill"
        iconWeight="semibold"
        className={twJoin(
          "hidden text-N60 hover:text-N80",
          !hidden && "group-focus-within:flex group-hover:flex"
        )}
        onClick={handleClick}
      />
    </div>
  );
};
