import React from "react";
import { twMerge } from "tailwind-merge";
import style from "../../../style";
import clsx from "clsx";

export interface ButtonProps extends React.HTMLProps<HTMLButtonElement> {
  /**
   * Input Ref .
   */
  ref?: React.Ref<HTMLButtonElement>;
  /**
   * Html element that will be used as the main element.
   */
  html?: "button" | "div" | "span";

  /**
   * Button variation that will switch between styles for the Button .
   */
  variation?: "initial" | "default" | "primary" | "secondary";

  /**
   * A string that will be added at the ond of the className and override any TailwindCss classes
   */
  className?: string;

  /**
   * Toggle Ripple effect on click of the button.
   */
  ripple?: boolean;
}

const Button: React.FC<ButtonProps> = React.forwardRef((props, ref) => {
  const {
    html,
    title,
    disabled,
    ripple,
    className,
    children,
    variation,
  } = props;

  let initialCss = style.button.init;
  if (ripple && !disabled) initialCss += " ripple ";
  if (disabled) initialCss += " opacity-70 cursor-not-allowed ";

  const variationClasses = clsx({
    [style.button.default]: variation === "default",
    [style.button.primary]: variation === "primary",
    [style.button.secondary]: variation === "secondary",
  });

  const elementProps = Object.assign({}, props);
  delete elementProps.ripple;
  delete elementProps.children;

  const classesMerged = `${initialCss} ${variationClasses} ${
    className ? className : ""
  }`;

  return React.createElement(
    html ? html : "button",
    {
      ...elementProps,
      className: twMerge(classesMerged),
      "aria-label": title,
      alt: title,
      ref: ref,
    },
    children
  );
});

Button.defaultProps = {
  ripple: false,
  variation: "initial",
};

Button.displayName = "Button";

export default Button;
