import React from "react";
import { twMerge } from "tailwind-merge";
import Block from "../Block";
import "./loader.css";

export interface LoaderProps {
  /**
   * Object that can contain override tw classes for the root and all inner elements
   */
  classes?: LoaderClasses;
  /**
   * Loading message, default: 'Loading ...'
   */
  message?: string;
  /**
   * If the loader is inline. It will render a small white animated circle to be used inside buttons or simillar elements.
   */
  isInline?: boolean;
  /**
   * Width of the SVG animated circle stroke.
   */
  strokeWidth?: string;
}

export interface LoaderClasses {
  /**
   * Tailwind Css classes for the main container of the loader
   */
  root?: string;
  /**
   * Tailwind Css classes for svg that is animated
   */
  svg?: string;
  /**
   * Tailwind Css classes for the text message of the Loader
   */
  message?: string;
}

const Loader: React.FC<
  LoaderProps & React.PropsWithRef<JSX.IntrinsicElements["svg"]>
> = (props) => {
  const { isInline, strokeWidth, message, classes } = props;

  const fixedStyles = !isInline
    ? "absolute inset-0 z-50 bg-white flex justify-center items-center flex-col"
    : "";

  const mergedClasses: LoaderClasses = {
    root: twMerge(`${fixedStyles} ${classes?.root}`),
    svg: twMerge(`${isInline ? "w-5" : "w-16"} ${classes?.svg}`),
    message: twMerge(` text-md text-inherit pt-5 ${classes?.message}`),
  };

  return !isInline ? (
    <Block
      style={!isInline ? { margin: "0" } : undefined}
      className={mergedClasses?.root}
    >
      <svg className={mergedClasses?.svg} viewBox="0 0 50 50">
        <circle
          stroke="currentColor"
          strokeLinecap={"round"}
          strokeWidth={strokeWidth}
          className="q-ds-spinner-path"
          cx="25"
          cy="25"
          r="20"
          fill="none"
        ></circle>
      </svg>
      <div className={mergedClasses?.message}>{message}</div>
    </Block>
  ) : (
    <Block className={mergedClasses?.root}>
      <svg className={mergedClasses?.svg} viewBox="0 0 50 50">
        <circle
          stroke="currentColor"
          strokeLinecap={"round"}
          strokeWidth={strokeWidth}
          className="q-ds-spinner-path"
          cx="25"
          cy="25"
          r="20"
          fill="none"
        ></circle>
      </svg>
    </Block>
  );
};
Loader.defaultProps = {
  message: "Loading ...",
  strokeWidth: "1",
};

export default Loader;
