import React, { ChangeEvent, ChangeEventHandler, RefObject } from "react";

import { twJoin } from "tailwind-merge";
import { InputButton } from "./InputButton";
import type { InputProps } from "./Input";

export interface ClearButtonProps {
  height: InputProps["height"];
  hidden?: boolean;
  onChange?: ChangeEventHandler<HTMLInputElement>;
  onClear?: () => void;
  inputRef?: RefObject<HTMLInputElement>;
}

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

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

  return (
    <div
      className={twJoin(
        "self-start",
        height === "32" ? "h-32 py-6" : "h-40 py-10",
        "min-w-[20px]"
      )}
    >
      <InputButton
        aria-label="Leegmaken"
        icon="xmark-circle-fill"
        iconWeight="semibold"
        className={twJoin(
          "sr-only text-N60 hover:text-N80",
          !hidden && "group-focus-within:not-sr-only group-hover:not-sr-only"
        )}
        onClick={handleClick}
      />
    </div>
  );
};
