import {
  useOptimisticActions,
  useWixPatternsContainer,
} from '@wix/bex-core/react';
import { AiAssistant, createWixPatternsCreationEventName } from './aiAssistant';
import { CollectionState, FiltersMap } from '@wix/bex-core';
import { useAiAssistantContext } from './useAiAssistantContext';
import { LoadingRowState } from '../components/LoadingRow/LoadingRowState';
import { useState } from 'react';
import { wixPatternsItemCreatedWithAiSrc144Evid3 } from '@wix/bex-core/bi';

export interface CreateAiAssistantProps {
  /** App def id of your ai-assistant */
  appDefId: string;
}
export function createAiAssistant({
  appDefId,
}: CreateAiAssistantProps): AiAssistant {
  return {
    useAiAssistant: <T, F extends FiltersMap>({
      collection,
      loadingRowState,
    }: {
      collection: CollectionState<T, F>;
      loadingRowState: LoadingRowState;
    }): void => {
      useAiAssistantCreation({ appDefId, collection, loadingRowState });
    },
  };
}

function useAiAssistantCreation<T, F extends FiltersMap>(props: {
  collection: CollectionState<T, F>;
  loadingRowState: LoadingRowState;
  appDefId: string;
}) {
  const { appDefId, collection, loadingRowState } = props;
  const optimisticActions = useOptimisticActions(collection);
  const { useAssistantEffect } = useAiAssistantContext();
  const { reportBi } = useWixPatternsContainer();
  useState(() => {
    loadingRowState._loadAnimationAssets();
  });

  useAssistantEffect<{ item?: T }>(
    (payload) => {
      if (!payload.item) {
        if (process.env.NODE_ENV !== 'production') {
          console.warn(
            'No item provided in the payload. Pass the new item that should be added to the collection like {item: myNewItem}. Skipping creation.',
          );
        }
        return;
      }

      const itemKey = collection.itemKey(payload.item);

      loadingRowState.addLoadingItem(itemKey);

      reportBi(
        wixPatternsItemCreatedWithAiSrc144Evid3({
          itemId: itemKey,
        }),
      );

      optimisticActions.createOne(payload.item, {
        submit: async (newItem) => {
          return newItem;
        },
      });
    },
    appDefId,
    createWixPatternsCreationEventName(collection),
  );
}
