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"];
  onChange: ChangeEventHandler<HTMLInputElement>;
  onClear?: () => void;
  inputRef: RefObject<HTMLInputElement>;
}

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

    onClear && 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"
      )}
    >
      <InputButton
        type="button"
        aria-label="Leegmaken"
        icon="xmark-circle-fill"
        iconWeight="semibold"
        className="hidden text-N60 hover:text-N80 disabled:hover:text-N60 group-focus-within:flex group-hover:flex"
        onClick={handleClick}
      />
    </div>
  );
};
