"use client";

import cx from "classnames";
import React, { ReactNode } from "react";

import { useStatic } from "../../utils/hooks";

import LoaderStatic from "./Loader.static";

const CLASS_ROOT = "loader";

interface LoaderProps {
  colour?: "default" | "inverse";
  isDelayed?: boolean;
  /** Messages that the loader will cycle until done */
  messages?: string[];
  /** Size variants */
  size?: "default" | "large";
  className?: string;
  children?: ReactNode;
  [key: string]: any;
}

const Loader: React.FC<LoaderProps> = ({
  messages,
  size = "default",
  className,
  colour = "default",
  isDelayed,
  children,
  ...other
}) => {
  const [loaderRef] = useStatic(LoaderStatic, { messages, isDelayed });

  const classes = cx(
    CLASS_ROOT,
    {
      [`${CLASS_ROOT}--${size}`]: size !== "default",
      [`${CLASS_ROOT}--${colour}`]: colour !== "default",
      hide: isDelayed,
    },
    className,
  );

  return (
    <div className={classes} {...other}>
      <div className={`${CLASS_ROOT}__body`}>
        <div className={`${CLASS_ROOT}__line`} />
      </div>
      {messages && (
        <div
          data-loader
          data-loader-delayed={isDelayed}
          data-loader-messages={JSON.stringify(messages)}
          className={`${CLASS_ROOT}__messages`}
          ref={loaderRef}
        >
          {children}
        </div>
      )}
    </div>
  );
};

Loader.displayName = "Loader";

export { Loader };
