import React, { ComponentType, useEffect, useState } from 'react';
import { Page } from '@wix/design-system';
import { useFormPageContext } from '../../providers/FormPageContext';
import { FormPageActionsBarProps } from '../../components/FormPage';

export function FormFooter({
  FooterElement,
  scrollableRef,
}: {
  FooterElement: ComponentType<FormPageActionsBarProps>;
  scrollableRef?: HTMLElement | null;
}) {
  const [scrollable, setScrollable] = useState<boolean>();
  const pageState = useFormPageContext();

  useEffect(() => {
    const pageStatus = pageState?.initTask?.status;
    if (!pageStatus.isLoading && !pageStatus.isIdle) {
      setScrollable(
        scrollableRef?.scrollHeight! > scrollableRef?.clientHeight!,
      );
    }
  }, [pageState?.initTask?.status]);

  return (
    <Page.Footer>
      <Page.Footer.End>{scrollable && <FooterElement />}</Page.Footer.End>
    </Page.Footer>
  );
}
