import React, { useState } from 'react';
import { Input, Flex } from 'antd';
// import { Input } from 'react-chat-elements';
import { useConversationState, useConversationDispatch } from '@/stores/ConversationContext';
import { useAuthContext } from '@/stores/AuthContext';
import { sentNewMessage } from '@/actions/ConversationActions';
import { SendOutlined } from '@ant-design/icons';
import { isEmpty } from '@/utils/utils';
import { v4 as uuid } from 'uuid';
import { sentMsgTypeMapped } from '@/lib/msgUtils';
import InputTemplate from './InputTemplate';

const InputBox = () => {
  const { loginUser } = useAuthContext();
  const { userId } = loginUser;
  const { websocket, currentConversation, } = useConversationState();
  const dispatch = useConversationDispatch();
  const [textContent, setTextContent] = useState('');

  const talkabled = !isEmpty(currentConversation.sn);

  const invokeSendMessage = (msgObj) => {
    console.log('sendMessage------------------', msgObj);
    const contentToSend = sentMsgTypeMapped[msgObj.type].contentToSend(msgObj);
    console.log('content to send-------------------------------------', contentToSend);
    websocket.sendMessage({ ...contentToSend, opi_sn: userId, coli_sn: currentConversation.coli_sn });
    const contentToRender = sentMsgTypeMapped[msgObj.type].contentToRender(msgObj);
    console.log(contentToRender, 'contentToRender  sendMessage------------------');
    dispatch(sentNewMessage(contentToRender));
  };

  const handleSendText = () => {
    if (textContent.trim() !== '') {
      const msgObj = {
        type: 'text',
        text: textContent,
        sender: 'me',
        to: currentConversation.whatsapp_phone_number,
        id: `${currentConversation.sn}.${uuid()}`, // Date.now().toString(16),
        date: new Date(),
        status: 'waiting',
      };
      invokeSendMessage(msgObj);
      setTextContent('');
    }
  };

  return (
    <div>
      <Flex gap={8}>
        <InputTemplate disabled={!talkabled} invokeSendMessage={invokeSendMessage} />
        <Input.Search
          disabled={!talkabled}
          placeholder='Type message here'
          // enterButton={'Send'}
          enterButton={<SendOutlined />}
          size='large'
          onSearch={handleSendText}
          value={textContent}
          onChange={(e) => setTextContent(e.target.value)}
        />
      </Flex>
      <div></div>
    </div>
  );
};

export default InputBox;
