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;
    /**
     * Toggle Ripple effect on click of the button.
     */
    highlighted?: boolean;
}

const Button: React.FC<ButtonProps> = React.forwardRef((props, ref) => {
    const { html, title, disabled, ripple, className, children, variation, highlighted } = 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 highlightedClasses = clsx({
        [' border-slate-100 bg-slate-100 ']: variation === 'initial',
        [' border-gray-200 bg-gray-300 ']: variation === 'default',
        [' bg-indigo-700 border-indigo-A700 ']: variation === 'primary',
        [' bg-gray-800 border-gray-800 ']: variation === 'secondary',
    });

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

    const classesMerged = `${initialCss}  ${variationClasses} ${highlighted ? highlightedClasses : ''} ${
        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;
