import { useEffect, useState } from 'react';
import { CustomFieldsWidgetState } from '../state';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import {
  ExtendedFields,
  parseFqdn,
  DefaultPermissionsConfig,
} from '@wix/bex-core';
import { useWidgetForm } from './useWidgetForm';

export interface UseCustomFieldsWidgetParams {
  fqdn: string;
  fieldName?: string;
  filterable?: boolean;
  containsPii?: boolean;
  defaultPermissions?: DefaultPermissionsConfig;
  extendedFields?: ExtendedFields;
}

export function useCustomFieldsWidget({
  fqdn: fqdnString,
  fieldName = 'extendedFields',
  filterable,
  containsPii,
  defaultPermissions,
  extendedFields,
}: UseCustomFieldsWidgetParams) {
  const fqdn = parseFqdn(fqdnString);
  const container = useWixPatternsContainer();
  const widgetForm = useWidgetForm();

  const [{ state, appLoaded }] = useState(() => {
    const widgetState = new CustomFieldsWidgetState({
      fqdn,
      container,
      filterable,
      containsPii,
      defaultPermissions,
      extendedFields,
    });

    widgetForm?.registerWidget(fieldName, widgetState);

    return {
      state: widgetState,
      appLoaded: widgetState._appLoadingStart(),
    };
  });

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

  return state;
}
