import type { ElementType } from "react";

import Link from "next/link";
import React from "react";

export type Props = {
  appearance?: "default" | "primary" | "secondary";
  className?: string;
  el?: "a" | "button" | "link";
  form?: string;
  href?: string;
  label?: string;
  newTab?: boolean | null;
  onClick?: () => void;
  isLoading?: boolean;
};

export const Button: React.FC<Props> = ({
  className: classNameFromProps,
  el = "button",
  form,
  href,
  label,
  newTab,
  isLoading,
}) => {
  const newTabProps = newTab ? { rel: "noopener noreferrer", target: "_blank" } : {};
  const Element: ElementType = el;
  const className = [classNameFromProps].filter(Boolean).join(" ");

  const elementProps = {
    ...newTabProps,
    className,
    form,
    href,
  };

  return (
    <Element {...elementProps} className="button button-primary-outline" {...{ disabled: isLoading }}>
      <React.Fragment>
        {(el === "link" || el === "a") && (
          <Link {...newTabProps} href={href || ""}>
            {label}
          </Link>
        )}
        {el === "button" && (
          <>
            {label} {isLoading && <span className="fa fa-spinner animate-spin ml-2" />}
          </>
        )}
      </React.Fragment>
    </Element>
  );
};
