import React, { ReactNode, useMemo, useRef } from 'react';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { SchemaConfig } from '../types/SchemaConfig';
import { SchemaContext, SchemaContextValue } from './SchemaContext';
import { CmsFieldModalState } from '../components/CmsFieldManagement/CmsFieldModalState';
import { CmsFieldModal } from '../components/CmsFieldManagement/CmsFieldModal';

interface SchemaProviderProps {
  schema: SchemaConfig;
  children?: ReactNode;
}

export const SchemaProvider = ({ schema, children }: SchemaProviderProps) => {
  const container = useWixPatternsContainer();

  const schemaRef = useRef(schema);
  schemaRef.current = schema;

  const modalState = useMemo(
    () =>
      new CmsFieldModalState(
        () => schemaRef.current,
        (e) =>
          container.errorHandler?.getResolvedError?.(e) ?? {
            message: e instanceof Error ? e.message : String(e),
          },
      ),
    [container],
  );

  const value = useMemo<SchemaContextValue>(
    () => ({
      schema,
      ...(schema.fieldActions?.addField && {
        addField: () => modalState.open(),
      }),
      ...(schema.fieldActions?.editField && {
        editField: (fieldId: string) => modalState.open(fieldId),
      }),
    }),
    [schema, modalState],
  );

  return (
    <SchemaContext.Provider value={value}>
      {children}
      <CmsFieldModal state={modalState} />
    </SchemaContext.Provider>
  );
};
