import { CollectionState, FiltersMap } from '@wix/bex-core';
import { ViewsState } from '../state';
import { useState } from 'react';
import { View, ViewsDTO } from '../model';
import { AppSettingsViewsSchema } from '../services';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import {
  getGlobalSettings,
  setGlobalSettings,
} from '@wix/bex-utils/@wix/ambassador-app-settings-v1-settings/http';
import { Host } from '@wix/bex-utils/@wix/ambassador-app-settings-v1-settings/types';

export interface MigrateOrdersViewsState<F extends FiltersMap> {
  _migrateOrdersViews?: (state: ViewsState<F>) => Promise<void>;
}

export function useMigrateOrdersViews<T, F extends FiltersMap>(
  collectionState: CollectionState<T, F>,
) {
  const { errorMonitor, httpClient } = useWixPatternsContainer();

  useState(() => {
    const ordersViewSettingsKey = 'orders.views';

    (collectionState as MigrateOrdersViewsState<F>)._migrateOrdersViews =
      async (state) => {
        const { viewsService } = state;
        const { viewsStorage, fqdn } = viewsService;

        try {
          const { data } = await httpClient.request(
            getGlobalSettings({
              host: Host.BUSINESS_MANAGER,
            }),
          );

          const legacyViews = data?.settings?.[ordersViewSettingsKey] as
            | (ViewsDTO<F> & { _migrationDate?: unknown })
            | undefined
            | null;

          // no views from old orders views app-settings
          if (legacyViews == null) {
            return;
          }

          // already migrated
          if (legacyViews._migrationDate) {
            return;
          }

          const viewsDiff = legacyViews.views;
          const hiddenPresetIdsDiff = legacyViews.hiddenPresetIds;

          const now = Date.now();

          const mergedViews: AppSettingsViewsSchema<F> = {
            views: {
              list: viewsDiff?.reduce((list, view, index) => {
                list[view.id] = {
                  ...view,
                  createdAt: new Date(now - index).toISOString(),
                };
                return list;
              }, {} as Record<string, View<F>>),
              hiddenPresetIds: hiddenPresetIdsDiff?.reduce(
                (hiddenPresetIds, id) => {
                  hiddenPresetIds[id] = id;
                  return hiddenPresetIds;
                },
                {} as Record<string, string>,
              ),
            },
          };

          await Promise.all([
            viewsStorage.setItem<AppSettingsViewsSchema<F> | null | undefined>(
              fqdn,
              mergedViews,
            ),
            httpClient.request(
              setGlobalSettings({
                host: Host.BUSINESS_MANAGER,
                settings: {
                  [ordersViewSettingsKey]: {
                    _migrationDate: new Date(),
                  },
                },
              }),
            ),
          ]);
        } catch (e) {
          errorMonitor.captureException(e);
        }
      };
  });
}
