import React, { useEffect, useRef, useState } from 'react';
import { useFormPageContext } from '../../providers';
import { observer } from 'mobx-react-lite';
import { CardContainer, CardContainerProps } from '../CardContainer';
import { FocusableProps, withFocusable } from '@wix/bex-utils';

export interface FormPageCardProps extends CardContainerProps {}

export function _FormPageCard(props: FormPageCardProps & FocusableProps) {
  const { status: statusProp, id, registerScrollableItem, ...rest } = props;
  const pageState = useFormPageContext();
  const status = !pageState || pageState.isFetching ? 'loading' : statusProp;
  const [highlight, setHighlight] = useState<'focus'>();
  const timeoutRef = useRef<number>();

  useEffect(() => {
    return () => {
      window.clearTimeout(timeoutRef.current);
    };
  });

  return (
    <div
      id={id}
      ref={(ref) => {
        if (id && ref) {
          registerScrollableItem({
            ref,
            itemName: id,
            containerName: id,
            afterScroll: () => {
              setHighlight('focus');

              timeoutRef.current = window.setTimeout(() => {
                setHighlight(undefined);
              }, 3000);
            },
          });
        }
      }}
    >
      <CardContainer status={status} {...rest} highlight={highlight} />
    </div>
  );
}

_FormPageCard.displayName = 'FormPageCard';

export const FormPageCard = withFocusable(observer(_FormPageCard));
