// Hooks
import React, { FC, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useStore } from 'stores/StoreProvider';
import { useNCIRCCMessages } from '../i18n';

// Apps
import { openNotificationError } from 'components/Messages';
import { NCIRCCNotificationsList } from './NCIRCCNotifications/NCIRCCNotificationsList';
import { NCIRCCIncidentMessenger } from './NCIRCCIncidentMessenger';
import { CardInfoDrawer } from 'components/Modals/CardInfoDrawer/CardInfoDrawer';
import StatusWithButtonUuid from '../components/StatusWithButtonUuid';
import { IncidentsCardInfo } from 'pages/IncidentsDashboard/IncidentsCardInfo';

// Antd
import { Button, Input } from 'antd';

// Stores
import { RootStore } from 'stores/RootStore';

//Styles
import classNames from 'classnames';
import styles from './Messages.module.scss';

export const NcirccMessages: FC = observer(() => {
  const rootStore: RootStore = useStore();
  const ncirccUiStore = rootStore.ncirccUiStore;
  const incidentsUiStore = rootStore.incidentsUiStore;
  const incidentsStore = rootStore.incidentsStore;

  const {
    allNotification,
    fetchAllNotification,
    postCommentsOnId,
    getCommentsOnId,
    getSelectedMessage,
  } = ncirccUiStore;

  const { fetchSelectedIncident } = incidentsUiStore;

  const { ncirccNotificationMessages } = useNCIRCCMessages();

  const [valueInputMessage, setValueInputMessage] = useState('');

  useEffect(() => {
    return () => incidentsStore.resetSelectedIncident();
  }, [incidentsStore, incidentsStore.resetSelectedIncident]);

  useEffect(() => {
    fetchAllNotification();
  }, [
    ncirccUiStore.fetchAllNotification,
    ncirccUiStore.getMessagePaginationState.current,
    ncirccUiStore.getMessagePaginationState.pageSize,
  ]);

  const handleOpenIncidentInfo = async (incidentId: string): Promise<void> => {
    try {
      incidentsUiStore.setIncidentCardSize('small');
      await fetchSelectedIncident(incidentId);
    } catch (e) {
      console.error(e);
    }
  };

  const postMessage = async (): Promise<void> => {
    try {
      await postCommentsOnId(valueInputMessage);
      setValueInputMessage('');
    } catch (e) {
      openNotificationError({
        messageTitle: ncirccNotificationMessages.messengerPostMessageErrorTitle,
        messageDescription:
          ncirccNotificationMessages.messengerPostMessageErrorSubTitle,
      });
    }
  };

  const onEnterPostMessage = async (
    event: React.KeyboardEvent<HTMLInputElement>,
  ): Promise<void> => {
    if (event.key === 'Enter' && valueInputMessage.trim()) {
      await postMessage();
    }
  };

  const onHandlePostMessage = async (): Promise<void> => {
    await postMessage();
  };

  const currentNotification = allNotification.find(
    (item) => item.id === getSelectedMessage,
  );

  const onCloseCard = (): void => {
    ncirccUiStore.setMessagesCardSize(undefined);
  };

  return (
    <div className={styles['container']}>
      <div
        className={classNames(styles['wrapper'], {
          [styles['wrapper--no-data']]: !allNotification.length,
        })}
      >
        {allNotification.length ? (
          <>
            <NCIRCCNotificationsList />
            <CardInfoDrawer
              cardSize={ncirccUiStore.messageCardSize}
              onCloseCard={onCloseCard}
              title={
                <StatusWithButtonUuid
                  loading={ncirccUiStore.getIsMessagesLoading}
                  handleOpenIncidentInfo={async () => {
                    if (currentNotification?.incident) {
                      await handleOpenIncidentInfo(
                        currentNotification.incident,
                      );
                    }
                  }}
                  category={currentNotification?.category}
                  uuid={currentNotification?.uuid}
                />
              }
              drawerFooter={
                <Input.Group>
                  <Input
                    style={{ width: 'calc(100% - 110px)' }}
                    value={valueInputMessage}
                    onChange={(event) =>
                      setValueInputMessage(event.target.value)
                    }
                    onKeyUp={(e) => onEnterPostMessage(e)}
                    placeholder={
                      ncirccNotificationMessages.messengerInputPlaceholder
                    }
                  />
                  <Button
                    disabled={!valueInputMessage.trim()}
                    type="primary"
                    onClick={onHandlePostMessage}
                  >
                    {ncirccNotificationMessages.messengerInputSubmit}
                  </Button>
                </Input.Group>
              }
            >
              <NCIRCCIncidentMessenger
                messages={getCommentsOnId}
                locale={{ noMessage: ncirccNotificationMessages.noMessage }}
              />
            </CardInfoDrawer>
            <IncidentsCardInfo parentPage="ncirccMessages" />
          </>
        ) : (
          <div className={styles['empty-text']}>
            {ncirccNotificationMessages.notificationNoData}
          </div>
        )}
      </div>
    </div>
  );
});
