import React, { useEffect, useState } from 'react';
import {
  WixPatternsDashboardBaseProvider,
  WixPatternsProviderProps,
} from './WixPatternsDashboardBaseProvider';
import { testkit } from '@wix/bex-utils/@wix/bex-bundled-mini-essentials/testkit';
import { whenRequest } from '@wix/bex-utils/@wix/bex-bundled-mini-essentials/http-client/testkit/client';
import {
  exportServiceMocks,
  appSettingsMocks,
} from '@wix/bex-core/testkit/client';
import { dataExtensionServiceMocks } from '../test-utils/dataExtensionServiceMocks';
import { tagsServiceMocks } from '../test-utils/tagsServiceMocks';
import { asyncJobMocks } from '../test-utils/AsyncJobMocks';
import { dashboard } from '@wix/dashboard';

export function WixPatternsDashboardTestProvider(
  props: WixPatternsProviderProps,
) {
  const [environment] = useState(() => ({
    language: 'en',
    locale: 'en',
    pageLocation: {
      pageId: '',
      pathname: '',
      search: '',
      hash: '',
    },
    embedded: false,
  }));

  const [essentials] = useState(() =>
    testkit.getTestContext({
      experiments: {
        bag: {},
      },
      httpClient: {
        scenarios: [
          ...appSettingsMocks(whenRequest),
          ...exportServiceMocks(whenRequest).mocks,
          ...dataExtensionServiceMocks(whenRequest).mocks,
          ...asyncJobMocks(whenRequest).mocks,
          ...tagsServiceMocks(whenRequest).mocks,
        ],
      },
    }),
  );

  useEffect(() => {
    const state = {
      mounted: true,
      afterAll: null as (() => void) | null,
    };
    testkit.beforeAll().then(({ afterAll }) => {
      state.afterAll = afterAll;
      if (!state.mounted) {
        afterAll();
      }
    });

    return () => {
      state.mounted = false;
      state.afterAll?.();
    };
  }, []);

  return (
    <WixPatternsDashboardBaseProvider
      {...props}
      dashboard={dashboard}
      environment={environment}
      essentials={essentials}
    />
  );
}
