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

import { InputButton } from "./InputButton";

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

export const ClearButton = ({
  onChange,
  inputRef,
  onClear,
}: ClearButtonProps) => (
  <InputButton
    // TODO: localize this when we find a way
    type="button"
    aria-label="Ontruimen"
    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={() => {
      onChange({
        target: { value: "" },
      } as ChangeEvent<HTMLInputElement>);

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