import React, {CSSProperties, ReactNode} from "react";
import "./formbutton.scss";
import Loader from "../../Loader/Loader";

type FormButtonProps = {
    onClick?: () => void;
    buttonType?: "submit" | "button";
    disabled?: boolean;
    children: ReactNode | ReactNode[];
    className?: string
    loading?: boolean
    style?: CSSProperties
};

const isSvg = (node: ReactNode | undefined) => {
    if (node == null || typeof node !== 'object') return false;
    return 'type' in node && (node as any).type === 'img';
}

/**
 * used as constructor for other types of form buttons
 * needs one or two children (svg icon and/or text)
 */
const FormButton = ({
                        onClick,
                        buttonType = 'submit',
                        disabled = false,
                        loading = false,
                        children,
                        className,
                        style,
                    }: FormButtonProps) => {

    const items = React.Children.toArray(children);
    const [first, second] = items;

    return (
        <button
            disabled={disabled}
            type={buttonType}
            onClick={() => onClick && onClick()}
            className={`form-button ${className} ${loading && 'loading'}`}
            style={style}
        >
            {
                loading && isSvg(first) ?
                    <Loader color='white'/>
                    :
                    first
            }
            {
                second !== undefined && isSvg(second) &&
                <hr/>
            }
            {
                second !== undefined && (
                    loading && isSvg(second) ?
                        <Loader color='white'/>
                        :
                        second
                )
            }
        </button>
    );
};

export default FormButton;
