import {useRef} from 'react';
import {ExtendedMessage, ExtendedMessageType} from '@modules/chats/interfaces';
import {isAndroid} from '@shared/utils';

export const useInitialIndex = ({
  messages,
  enabled,
}: {
  messages: ExtendedMessage[];
  enabled: boolean;
}) => {
  const initialIndex = useRef<{index: number; viewPosition: number} | number>(
    -1,
  );

  if (messages.length > 0 && initialIndex.current === -1 && enabled) {
    let index: {index: number; viewPosition: number} | number = -1;

    index = messages.findIndex(
      msg =>
        msg.extendedType === ExtendedMessageType.UnreadPill &&
        msg.data.isLastRead,
    );

    const msgCount = messages.length;
    const msgLastIndex = msgCount - 1;

    if (index === -1) {
      // Workaround for Android
      index = isAndroid ? Math.max(msgCount - 2, 0) : msgLastIndex;
    } else {
      index = Math.min(msgLastIndex, index);
    }

    if (index === msgLastIndex) {
      index = {index, viewPosition: 1};
    }

    initialIndex.current = index;
  }

  return {initialIndex};
};
