import React, { FC, HTMLAttributes, Children, useState, useEffect, useRef, createContext, useMemo, startTransition, ReactNode } from "react";

import { Padding } from "../../index";
import { getCN, randomId } from '../utils'

import './ModalCard.css'

interface IModalCard extends HTMLAttributes<HTMLDivElement> {
  id: string,
  autoPadding?: boolean
  header?: ReactNode | string;
  background?: boolean;
  onClose?: React.ReactNode;
};

const ModalCard: FC<IModalCard> = ({
  id,
  children,
  header,
  onClose,
  background = true,
  ...restProps
}) => {

  const ref = React.useRef<HTMLDivElement>(null);
  const [size, setSize] = React.useState<number>();

  const resizeHandler = () => {
    if (ref.current) {
      const { offsetHeight, clientWidth } = ref.current;
      setSize(offsetHeight);
    }
  };

  useEffect(() => {
    resizeHandler();
  }, [
    ref.current && ref.current.offsetHeight,
    children,
    ref
  ]);

  useEffect(() => {
    bindImagesOnload(ref.current, function () {
      resizeHandler()
    });
  }, [children])


  return <div
    id={id}
    {...restProps}
    className={getCN(`ModalCard`, restProps.className)}
  >
    {!onClose && header && <div className={getCN(`ModalCard__header`)}>{header}</div>}
    {onClose && <div className={getCN(`ModalCard__onClose`)}>{onClose}</div>}

    <div style={{ height: size ? size : `100%` }} className={getCN(`ModalCard__in`)}>
      <div id={"children_" + id} ref={ref} className={getCN(`ModalCard__content`)}>
        {children}
      </div>
    </div>
  </div>
}

const bindImagesOnload = (node: any, fn: () => void) => {
  var imgs = node.getElementsByTagName("img"),
    length = imgs.length;
  var onload = () => fn();
  for (var i = 0; i < length; i++) imgs[i].onload = onload;
}

export default ModalCard;