import React, {
  ReactNode,
  RefObject,
  useState,
  useEffect,
  useRef,
} from 'react';
import { Box, Loader } from '@wix/design-system';
import { CustomFieldModalState } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';

const useElementWidth = <T extends Element>(
  initialWidth: number = 0,
): [number, RefObject<T>] => {
  const [width, setWidth] = useState<number>(initialWidth);
  const ref = useRef<T>(null);

  useEffect(() => {
    if (ref.current) {
      setWidth(ref.current.clientWidth);
    }
  }, [ref.current]);

  return [width, ref];
};

export interface CustomFieldModalPrimaryButtonProps {
  state: CustomFieldModalState;

  content: ReactNode;
}

export const CustomFieldModalPrimaryButton = observer(
  (props: CustomFieldModalPrimaryButtonProps) => {
    const {
      state: { isSubmitting },
      content,
    } = props;
    const [width, ref] = useElementWidth<HTMLDivElement>();

    return (
      <div ref={ref}>
        {isSubmitting ? (
          <Box verticalAlign="middle" align="center" width={width}>
            <Loader
              dataHook="custom-field-modal-status-submitting"
              size="tiny"
            />
          </Box>
        ) : (
          content
        )}
      </div>
    );
  },
);
