'use client';

import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Box, Tooltip, Button } from '@mui/material';
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome';
import { AppDispatch, getPreferences, getAdditionalData, selectAIDisabled, selectProfileAdditionalData } from './store';
import { setMinmize, clearMessages } from './store/chatSlice';
import { selectChatMinimized } from './store/chatSlice/selectors';
import { AiChat, MinimizedChat } from './components';


const AiAgent: React.FC = () => {

  const dispatch = useDispatch<AppDispatch>();
  const isMinimized = useSelector(selectChatMinimized);
  const [showAgent, setShowAgent] = useState(false);
  const [showTooltip, setShowTooltip] = useState(false);
  const AIDisabled = useSelector(selectAIDisabled);
  const isOpenedBefore = useSelector(selectProfileAdditionalData).is_ai_agent_opened;

  useEffect(() => {
    dispatch(getPreferences());
    dispatch(getAdditionalData('is_ai_agent_opened'));
  }, []);

  const handleOpen = () => {
    setShowAgent(true);
    setShowTooltip(false);
    dispatch(setMinmize(false));
  };

  const handleClose = () => {
    setShowAgent(false);
    dispatch(setMinmize(false));
  };

  const handleClearHistory = () => {
    dispatch(clearMessages());
  };

  const handleMinimize = () => {
    dispatch(setMinmize(true));
    setShowAgent(false);
  };

  if (AIDisabled) {
    return <></>
  }

  return (
    <>
      <Box sx={{ ml: 2 }}>
        <Tooltip
          title="Try new AI agent"
          placement="bottom"
          arrow
          open={showTooltip}
          onClose={() => setShowTooltip(false)}
          onOpen={() => setShowTooltip(true)}
        >
          <Button onClick={handleOpen} color='primary' variant='text' sx={{ minWidth: 'auto' }}>
            <AutoAwesomeIcon sx={{ animation: isOpenedBefore ? '' : 'float-smooth 2s ease-in-out infinite' }} />
          </Button>
        </Tooltip>
      </Box>
      {showAgent && <AiChat onClose={handleClose} onMinimize={handleMinimize} onHistoryClear={handleClearHistory} />}
      {isMinimized && <MinimizedChat onClose={handleClose} onOpen={handleOpen} />}
    </>
  );
};

export default AiAgent;
