import React, { useState } from 'react';
import { w3cwebsocket as W3CWebSocket } from 'websocket';
import crypto from 'crypto';

import './style.css';
import ChatBotUI from './ChatBotUI';
import SmartToyIcon from '@mui/icons-material/SmartToy';

const Chatbot = ({ URL, Icon, Style }) => {
  const [showBot, toggleBot] = useState(false);

  const ws = new W3CWebSocket(
    `${URL}/${crypto.randomBytes(20).toString('hex')}`
  );
  //Websocket On Connect
  ws.onopen = () => {
    console.log('Connected');
  };
  //Websocket On Close
  ws.onclose = (event) => {
    console.error(event);
    console.log('Websocket Closed');
    // window.close();
  };

  ws.onerror = (event) => {
    console.log('Error occured');
    console.error('WebSocket error observed:', event);
  };

  return (
    <>
      {showBot && <ChatBotUI ws={ws} Style={Style} />}

      <button
        className={
          Style.botButtonPosition === 'right'
            ? `bot-button-right`
            : 'bot-button-left'
        }
        onClick={() => {
          toggleBot((prev) => !prev);
        }}
      >
        {Icon ? Icon : <SmartToyIcon />}
      </button>
    </>
  );
};

export default Chatbot;
