import React from 'react';
import { clsx } from 'clsx';

import * as css from './skeleton.css';

/*-- Types --*/

type SkeletonChild = React.ReactElement<{
  className?: string;
  children?: React.ReactNode;
}>;

export interface SkeletonWrapperProps extends css.SkeletonWrapperVariants {
  children: SkeletonChild | SkeletonChild[];
  loading?: boolean;
  fallback?: React.ReactNode;
}

/*-- Main --*/

export function SkeletonWrapper({
  children,
  height,
  fallback,
  loading = true,
}: SkeletonWrapperProps) {
  return (
    <>
      {loading
        ? React.Children.map(children, child =>
            React.isValidElement(child)
              ? React.cloneElement(
                  child,
                  {
                    className: clsx(
                      child.props.className,
                      css.skeletonWrapper({ height }),
                    ),
                  },
                  fallback || child.props.children,
                )
              : child,
          )
        : children}
    </>
  );
}
