import { useContext, useReducer, useEffect } from 'react';
import { ConversationStateContext, ConversationDispatchContext } from '@/stores/ConversationContext';
import ConversationReducer from '@/reducers/ConversationReducer';
import {
  initWebsocket,
  updateWebsocketState,
  updateWebsocketRetrytimes,
  addError,
  fetchConversationsList,
  fetchTemplates,
  receivedConversationList,
  receivedTemplates,
  updateMessageItem,
  receivedNewMessage,
} from '@/actions/ConversationActions';
import initialState from '@/records/ConversationState';

import { AuthContext } from '@/stores/AuthContext';

import { RealTimeAPI } from '@/lib/realTimeAPI';
import { receivedMsgTypeMapped } from '@/lib/msgUtils';
import { isEmpty } from '@/utils/utils';

// const WS_URL = 'ws://202.103.68.144:8888/whatever/';
// const WS_URL = 'ws://120.79.9.217:10022/whatever/';
const WS_URL = 'wss://p9axztuwd7x8a7.mycht.cn/whatsapp_callback'; // prod:

const ConversationProvider = ({ children }) => {
  const { loginUser } = useContext(AuthContext);
  const { userId } = loginUser;

  const [state, dispatch] = useReducer(ConversationReducer, { ...initialState, websocket: null });

  console.log('ConversationProvider', state, dispatch);

  // useEffect(() => {
  //   console.log('invoke provider');
  //   const realtimeAPI = new RealTimeAPI(
  //     {
  //       url: `${WS_URL}?opisn=${userId || ''}&_spam=${Date.now().toString()}`,
  //       protocol: 'WhatsApp',
  //     },
  //     () => {dispatch(updateWebsocketState(true)); dispatch(updateWebsocketRetrytimes(0));},
  //     () => dispatch(updateWebsocketState(false)),
  //     (n) => dispatch(updateWebsocketRetrytimes(n))
  //   );

  //   realtimeAPI.onError(() => dispatch(addError('Error')));
  //   realtimeAPI.onMessage(handleMessage);
  //   realtimeAPI.onCompletion(() => dispatch(addError('Connection broken')));

  //   dispatch(initWebsocket(realtimeAPI));
  //   return () => {
  //     realtimeAPI.disconnect();
  //   };
  // }, []);

  // useEffect(() => {
  //   fetchConversationsList({ opisn: userId }).then((data) => {
  //     dispatch(receivedConversationList(data));
  //   });

  //   fetchTemplates().then((data) => dispatch(receivedTemplates(data)));

  //   return () => {};
  // }, []);
  const handleMessage = (data) => {
    console.log('handleMessage------------------');
    console.log(data);
    const { errcode, errmsg, result } = data;

    if (!result) {
      return false;
    }
    let resultType = result?.action || result.type;
    if (errcode !== 0) {
      // addError('Error Connecting to Server');
      resultType = 'error';
    }
    console.log(resultType, 'result.type');
    const msgObj = receivedMsgTypeMapped[resultType].getMsg(result);
    const msgRender = receivedMsgTypeMapped[resultType].contentToRender(msgObj);
    const msgUpdate = receivedMsgTypeMapped[resultType].contentToUpdate(msgObj);
    console.log('msgRender msgUpdate', msgRender, msgUpdate);
    if (['whatsapp.message.updated', 'message', 'error'].includes(resultType)) {
      dispatch(updateMessageItem(msgUpdate));
      // return false;
    }
    if (!isEmpty(msgRender)) {
      dispatch(receivedNewMessage(msgRender.conversationid, msgRender));
    }
    console.log('handleMessage*******************');
  };
  // return <ConversationContext.Provider value={{ ...state, dispatch }}>{children}</ConversationContext.Provider>;
  return (
    <ConversationStateContext.Provider value={{ ...state }}>
      <ConversationDispatchContext.Provider value={dispatch}>{children}</ConversationDispatchContext.Provider>
    </ConversationStateContext.Provider>
  );
};

export default ConversationProvider;
