import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { NPCDialogType } from '../..';
import { IS_MOBILE_OR_TABLET } from '../../constants/uiDevices';
import { chunkString } from '../../libs/StringHelpers';
import { DynamicText } from '../typography/DynamicText';
import pressButtonGif from './img/press-button.gif';
import pressSpaceGif from './img/space.gif';

interface IProps {
  text: string;
  onClose: () => void;
  onEndStep?: () => void;
  onStartStep?: () => void;
  type?: NPCDialogType;
}

export const NPCDialogText: React.FC<IProps> = ({
  text,
  onClose,
  onEndStep,
  onStartStep,
  type,
}) => {
  const windowSize = useRef([window.innerWidth, window.innerHeight]);
  function maxCharacters(width: number) {
    // Set the font size to 16 pixels
    var fontSize = 11.2;

    // Calculate the number of characters that can fit in one line
    var charactersPerLine = Math.floor(width / 2 / fontSize);

    // Calculate the number of lines that can fit in the div
    var linesPerDiv = Math.floor(180 / fontSize);

    // Calculate the maximum number of characters that can fit in the div
    var maxCharacters = charactersPerLine * linesPerDiv;

    // Return the maximum number of characters
    return Math.round(maxCharacters / 5);
  }

  const textChunks = chunkString(text, maxCharacters(windowSize.current[0]));

  const [chunkIndex, setChunkIndex] = useState<number>(0);
  const onHandleSpacePress = (event: KeyboardEvent) => {
    if (event.code === 'Space') {
      goToNextStep();
    }
  };

  const goToNextStep = () => {
    const hasNextChunk = textChunks?.[chunkIndex + 1] || false;

    if (hasNextChunk) {
      setChunkIndex(prev => prev + 1);
    } else {
      // if there's no more text chunks, close the dialog
      onClose();
    }
  };

  useEffect(() => {
    document.addEventListener('keydown', onHandleSpacePress);

    return () => document.removeEventListener('keydown', onHandleSpacePress);
  }, [chunkIndex]);

  const [showGoNextIndicator, setShowGoNextIndicator] = useState<boolean>(
    false
  );

  return (
    <Container>
      <DynamicText
        text={textChunks?.[chunkIndex] || ''}
        onFinish={() => {
          setShowGoNextIndicator(true);

          onEndStep && onEndStep();
        }}
        onStart={() => {
          setShowGoNextIndicator(false);

          onStartStep && onStartStep();
        }}
      />
      {showGoNextIndicator && (
        <PressSpaceIndicator
          right={type === NPCDialogType.TextOnly ? '1rem' : '10.5rem'}
          src={IS_MOBILE_OR_TABLET ? pressButtonGif : pressSpaceGif}
          onPointerDown={() => {
            goToNextStep();
          }}
        />
      )}
    </Container>
  );
};

const Container = styled.div``;

interface IPressSpaceIndicatorProps {
  right: string;
}

const PressSpaceIndicator = styled.img<IPressSpaceIndicatorProps>`
  position: absolute;
  right: ${({ right }) => right};
  bottom: 1rem;
  height: 20.7px;
  image-rendering: -webkit-optimize-contrast;
`;
