import React, { useEffect, useState } from 'react';

import { IModalContext, ModalContext } from './context/ModalContext';
import { Modal } from './modal/Modal';
import { ModalBody } from '../../../../engine/admin/static/llm-modal/modal/ModalBody';
import { ILlmInitAction, ModalDisplayStyle } from './common/interfaces';
import { getModalDataRequestBody, getPromptData } from './common/adminApiUtil';
import { getTargetText } from './common/textUtil';
import { ModalFooter } from './modal/ModalFooter';

interface AppProps {
   close: () => void;
   llmAction: ILlmInitAction;
   displayStyle: ModalDisplayStyle;
}

const getCleanState = (initAction: ILlmInitAction, prevState?: IModalContext): IModalContext => {
   return {
      ...initAction,
      initPrompt: '',
      promptId: prevState?.promptId ?? initAction.promptId,
      targetContent:
         prevState?.targetContent ?? initAction.targetText ?? getTargetText(initAction.target),
      editMode: false,
      responses: [],
      showResponseIndex: 0,
      objectPrompts: prevState?.objectPrompts ?? [],
      title: prevState?.title ?? initAction.title,
      loading: true,
      loadingResponse: false,
      updateState: undefined as any,
   };
};

export const App = (props: AppProps) => {
   const [state, setState] = useState<IModalContext>(getCleanState(props.llmAction));

   const updateState = (data: Partial<IModalContext>) => {
      setState((prevState) => {
         return { ...prevState, ...data } as IModalContext;
      });
   };

   useEffect(() => {
      const newState = getCleanState(props.llmAction, state);
      setState(newState);
      getPromptData(getModalDataRequestBody(newState)).then((val) => {
         updateState({ title: val.title, initPrompt: val.prompt, objectPrompts: val.prompts });
         updateState({ loading: false });
      });
   }, [props.llmAction, state?.promptId]);

   return (
      <ModalContext.Provider value={{ ...state, updateState } as IModalContext}>
         <Modal close={props.close} displayStyle={props.displayStyle}>
            <ModalBody />
            <ModalFooter close={props.close} />
         </Modal>
      </ModalContext.Provider>
   );
};
