import React, { useState } from 'react';
import { Input, Flex, Button } 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, MessageOutlined, SmileOutlined } 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, websocketOpened, currentConversation } = useConversationState();
  const dispatch = useConversationDispatch();
  const [textContent, setTextContent] = useState('');

  const talkabled = !isEmpty(currentConversation.sn) && websocketOpened;

  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>
      <Input.TextArea
        size='large'
        placeholder='Enter for Send, Shift+Enter for new line'
        rows={2}
        disabled={!talkabled}
        value={textContent}
        onChange={(e) => setTextContent(e.target.value)}
        className='rounded-b-none'
        onPressEnter={(e) => {
          if (!e.shiftKey) {
            e.preventDefault();
            handleSendText();
          }
        }}
        autoSize={{minRows: 2, maxRows: 6}}
      />
      <Flex justify={'space-between'} className=' bg-gray-200 p-1'>
        <Flex gap={4} className='divide-y-0 divide-x divide-solid divide-gray-500 '>
          <InputTemplate key='templates' disabled={!talkabled} invokeSendMessage={invokeSendMessage} />
        </Flex>
        <Button key={'send-btn'} type='primary' size='middle' icon={<SendOutlined />} disabled={!talkabled}>
          Send
        </Button>
      </Flex>
    </div>
  );
};

export default InputBox;
