import React, { ReactNode, useEffect, useState } from 'react';
import { FormPageContextProvider } from '@wix/bex-core/react';
import { PageWrapperBase } from '../PageWrapper';
import { FormPageState } from '@wix/bex-core';
import { FieldValues, useForm } from 'react-hook-form';

export function FormPageProvider<V extends FieldValues = FieldValues>({
  children,
  state,
}: {
  children: ReactNode;
  state?: FormPageState<V>;
}) {
  const newState = useForm<V>();
  const [formPageState] = useState(
    () => state ?? new FormPageState({ form: newState }),
  );

  const {
    form: {
      formState: { isSubmitSuccessful, isDirty },
    },
  } = formPageState;

  /* formState is wrapped with a Proxy to improve render performance and skip extra logic if specific state is not subscribed to.
  Therefore, make sure you invoke or read it before a render in order to enable the state update. */
  useEffect(() => {
    formPageState._isSubmitSuccessful = isSubmitSuccessful;
    formPageState._isFormDirty = isDirty;
  }, [isSubmitSuccessful, isDirty]);

  return (
    <FormPageContextProvider value={formPageState}>
      <PageWrapperBase>{children}</PageWrapperBase>
    </FormPageContextProvider>
  );
}
