import type { FC, ReactElement } from "react";
import { useMemo } from "react";
import ContentLoader from "react-content-loader";
import type { IContentLoaderProps } from "react-content-loader";
import type { IContentPlaceholder } from "./config/types";
import { getLinesProp } from "./utils/index";
import type { IComponentBaseProps } from "../../types/components/index";
import { useCN } from "../../utils/react/useCN";
import "./style.pcss";

const loaderModule = ContentLoader as FC<IContentLoaderProps> & {
  default?: FC<IContentLoaderProps>;
};

const Loader: FC<IContentLoaderProps> = process.env.NODE_ENV === "test" && loaderModule.default
  ? loaderModule.default
  : loaderModule;

/**
 * Компонент заглушки
 * @returns {ReactElement}

 */
const ContentPlaceholder: FC<IContentPlaceholder & IComponentBaseProps> = ({
  baseClass = "contentPlaceholder",
  children = null,
  extraClasses = {},
  extraAttrs = {},
  speed = 2,
  backgroundColor = "#ecebeb",
  foregroundColor = "#f3f3f3",
  width = 400,
  height = 264,
  preserveAspectRatio = "none",
  lines = 5,
  linesHeight = 40,
  linesBorderRadius = 8,
  linesMargin = 16,
  linesWidth = [ 400, 360, 320, 380, 240 ],
}): ReactElement => {

  const { getCN } = useCN(baseClass);

  const linesChildren = useMemo<ReactElement[]>(() => {
    let offsetY = 0;
    return new Array(lines)
      .fill("")
      .map((_line, index) => {
        const mb = getLinesProp(linesMargin, index);
        const height = getLinesProp(linesHeight, index);
        const width = getLinesProp(linesWidth, index);
        const br = getLinesProp(linesBorderRadius, index);
        const y = offsetY;
        offsetY += height + mb;
        const lineKey = `line_${y}_${width}_${height}_${br}`;
        return (
          <rect className={getCN("line")} key={lineKey} x={0} y={y} rx={br} ry={br} width={width} height={height} />
        );
      });
  }, [ lines, linesMargin, linesBorderRadius, linesWidth, linesHeight ]);

  return (
    <div className={getCN("", extraClasses)} {...extraAttrs} role={"progressbar"}>
      <Loader className={getCN("inner")} speed={speed} backgroundColor={backgroundColor}
        foregroundColor={foregroundColor} preserveAspectRatio={preserveAspectRatio}
        viewBox={`0 0 ${width} ${height}`}>
        {children || linesChildren}
      </Loader>
    </div>
  );

};

export type { IContentPlaceholder };
export { ContentPlaceholder };
