import { useEffect, useState } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { botType, bots, userKey } from "../constants";
import Wizard from "./Wizard";
import { Box } from '@mui/material';
import {
  dismissBot,
  loadBotSession,
  closeChat,
  saveMessage
} from "../actionCreators";

interface Props {
  bot: {
    type: string;
  };
  actions: {
    dismissBot: () => void;
    loadBotSession: (bot: string, userKey: string, type: string) => void;
    closeChat: () => void;
    saveMessage: (message: any) => void;
  };
}

const BotsManager: React.FC<Props> = ({ bot, actions }) => {
  const [type, setType] = useState(bot.type);

  useEffect(() => {
    if (!bot.type) return;
    setType(bot.type);

    if (bot.type === botType.none) return;
    actions.loadBotSession(bots.Zirhan, userKey.unknown, bot.type);
  }, [actions, bot.type]);

  const dismissBot = () => {
    actions.closeChat();
    actions.dismissBot();
  };

  return (
    <Box
      sx={{
        position: "fixed",
        bottom: 2,
        right: 2,
        zIndex: 1
      }}
    >
      {type === botType.wizard && (
        <Wizard dismissBot={dismissBot} saveMessage={actions.saveMessage} />
      )}
    </Box>
  );
};

function mapStateToProps(state: any) {
  return {
    bot: state.bot
  };
}

function mapDispatchToProps(dispatch: any) {
  return {
    actions: bindActionCreators(
      { dismissBot, loadBotSession, closeChat, saveMessage },
      dispatch
    )
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(BotsManager as any);