import React, { ReactNode, useEffect, useState } from 'react';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import {
  PatternsFieldsAppContainer,
  PatternsFieldsContainerProvider,
} from '@wix/patterns-fields/providers';
// eslint-disable-next-line no-restricted-imports
import '@wix/patterns-fields/src/styles.global.css';

/**
 * Initializes PatternsFieldsAppContainer with the current WixPatternsContainer
 * and exposes it via PatternsFieldsContainerProvider.
 *
 * Must be rendered inside a WixPatternsContainerProvider (e.g. inside CairoProviderCore).
 */
export const PatternsFieldsProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const patternsContainer = useWixPatternsContainer();

  const [fieldsContainer] = useState(
    () => new PatternsFieldsAppContainer({ patternsContainer }),
  );

  useEffect(() => {
    fieldsContainer.init();
  }, [fieldsContainer]);

  return (
    <PatternsFieldsContainerProvider value={fieldsContainer}>
      {children}
    </PatternsFieldsContainerProvider>
  );
};
