import React, { useState, useEffect, useRef } from 'react';
// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

import { Form } from 'react-final-form';

// Import actions here
import messagerieActions from 'store/messagerie/actions';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import ConversationCard from 'components/listItems/ConversationCard';
import MessagesForm from 'components/forms/MessagesForm';
import MessageCard from 'components/listItems/MessageCard';
import actionsBuilder from 'store/appActions';
import find from 'lodash/find';
import { pushRoute } from 'store/utils/routes';
import styleIdentifiers from './mailBox.scss';

// assets
import pp from './assets/pp.png';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type MailBoxProps = StateProps & DispatchProps & OwnProps;

const MailBox = (props: MailBoxProps) => {
  // mapStateToProps
  const {
    match: { params },
    history,
  } = props;

  const messageWrapper = useRef(null);

  const [initial, setInitial] = useState({});

  const lg = useSelector((state: StoreState) => state.content.lg);

  const messages = useSelector(
    (state: StoreState) => state.messagerie && state.messagerie.currentRoomMessages,
  );
  const roomsList = useSelector(
    (state: StoreState) => state.messagerie && state.messagerie.roomsList,
  );
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const profile = useSelector(
    (state: StoreState) => state.account.profile && state.account.profile.data,
  );

  const [author, setAuthor] = useState();

  const [selectedConvers, setSelectedConvers] = useState();

  const actions = actionsBuilder(dispatch, [
    'addMessageToRoom',
    'getRoomsList',
    'createRoom',
    'getRoomMessages',
  ]);

  const {
    messagerieAddMessageToRoom,
    messagerieGetRoomsList,
    messagerieCreateRoom,
    messagerieGetRoomMessages,
  } = actions;

  const getOtherGuy = conv => {
    // fallback to me
    const otherGuy =
      find(conv.getAccounts, account => {
        return account._id !== profile._id;
      }) || profile;

    return otherGuy;
  };

  const selectConvers = conv => {
    const otherGuy = getOtherGuy(conv);

    if (!otherGuy) return;

    setAuthor(`${otherGuy.firstName} ${otherGuy.lastName}`);

    setSelectedConvers(conv._id);

    history.push(
      pushRoute('mailBox.id', lg, {
        id: otherGuy._id,
      }),
    );
  };

  const getCurrentRoom = () => {
    if (!roomsList || !roomsList.data) return null;

    for (let i = 0; i < roomsList.data.length; i += 1) {
      const item = roomsList.data[i];

      const selected = find(item.getAccounts, person => {
        return person._id === params.id;
      });
      if (selected) return item;
    }
    return null;
  };

  const handleSubmit = (values, form) => {
    console.log(values, form);

    const convers = getCurrentRoom();

    if (!values.message) return;

    messagerieAddMessageToRoom({
      data: {
        roomId: convers._id,
        message: values.message,
      },
      callback: () => {
        // reinit message
        form.reset();
        if (messageWrapper.current)
          messageWrapper.current.scrollTop = messageWrapper.current?.scrollHeight;
      },
    });
  };

  const getConversationMessage = () => {
    if (!roomsList || !roomsList.data || roomsList.data.length === 0) return;

    if (!params.id) {
      for (let i = 0; i < roomsList.data.length; i += 1) {
        const item = roomsList.data[i];

        if (item.getAccounts && item.getAccounts.length > 1) {
          selectConvers(item);
          break;
        }
      }

      return;
    }

    const convers = getCurrentRoom();

    if (!convers) return;

    messagerieGetRoomMessages({
      id: convers._id,
      callback: res => {
        console.log(res);
        if (messageWrapper.current)
          messageWrapper.current.scrollTop = messageWrapper.current?.scrollHeight;
      },
    });

    const receiver = find(convers.getAccounts, account => {
      return account._id !== profile._id;
    });

    let name = 'No Name';
    if (receiver) name = `${receiver.firstName} ${receiver.lastName}`;
    setAuthor(name);
  };

  useEffect(() => {
    getConversationMessage();
  }, [params, roomsList]);

  useEffect(() => {
    if (!roomsList || !roomsList.data || roomsList.data.length === 0) {
      messagerieGetRoomsList({
        callback: () => {
          if (params.id) {
            messagerieCreateRoom({
              accountIds: [profile._id, params.id],
              callback: selectConvers,
            });
          }
        },
      });
    } else if (params.id) {
      messagerieCreateRoom({
        // params.id is here the account of the user
        accountIds: [params.id, profile._id],
        callback: selectConvers,
      });
    }
  }, []);

  let messagesData = (messages && messages.data) || [];
  console.log('messagesData', messagesData);
  messagesData = messagesData?.slice()?.reverse();

  const roomsData = (roomsList && roomsList.data) || [];

  return (
    <>
      {roomsList && roomsList.loaded && (
        <div className={styles('mail-box')}>
          {roomsData.length ? (
            <>
              <div className={styles('top')}>
                <h1 className={styles('title')}>
                  <TextItem path="pages.messages.title" />
                </h1>
              </div>
              <div className={styles('chat-wrapper')}>
                <div className={styles('cards-container')}>
                  {roomsData.map((conv, index) => {
                    return (
                      <ConversationCard
                        item={conv}
                        key={index}
                        selectedConvers={selectedConvers}
                        action={() => {
                          selectConvers(conv);
                        }}
                      />
                    );
                  })}
                </div>

                <div className={styles('chat-container')}>
                  <div className={styles('convers-container')} id="test" ref={messageWrapper}>
                    {messagesData.map((mess, index) => {
                      return (
                        <MessageCard
                          otherPerson={author}
                          item={mess}
                          key={index}
                          profile={profile}
                        />
                      );
                    })}
                    {!messagesData.length && messages && messages.loaded && (
                      <div className={styles('no-message')}>
                        <TextItem path="pages.messages.notStarted" />
                      </div>
                    )}
                  </div>
                  {params.id && (
                    <div className={styles('submit')}>
                      <Form
                        component={MessagesForm}
                        customClassName={styles('form')}
                        onSubmit={handleSubmit}
                      />
                    </div>
                  )}
                </div>
              </div>
            </>
          ) : (
            <div className={styles('no-message')}>
              <TextItem path="pages.messages.noConversation" />
            </div>
          )}
        </div>
      )}
    </>
  );
};

export default MailBox;
