import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { NPCDialog, NPCDialogType } from './NPCDialog/NPCDialog';
import { NPCMultiDialog, NPCMultiDialogType } from './NPCDialog/NPCMultiDialog';
import {
  IQuestionDialog,
  IQuestionDialogAnswer,
  QuestionDialog,
} from './NPCDialog/QuestionDialog/QuestionDialog';

export interface IHistoryDialogProps {
  backgroundImgPath: string[];
  fullCoverBackground: boolean;
  questions?: IQuestionDialog[];
  answers?: IQuestionDialogAnswer[];
  text?: string;
  imagePath?: string;
  textAndTypeArray?: NPCMultiDialogType[];
  onClose: () => void;
}

export const HistoryDialog: React.FC<IHistoryDialogProps> = ({
  backgroundImgPath,
  fullCoverBackground,
  questions,
  answers,
  text,
  imagePath,
  textAndTypeArray,
  onClose,
}) => {
  const [img, setImage] = useState<number>(0);
  const onHandleSpacePress = (event: KeyboardEvent) => {
    if (event.code === 'Space') {
      if (img < backgroundImgPath?.length - 1) {
        setImage(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);
  }, [backgroundImgPath]);
  return (
    <BackgroundContainer
      imgPath={backgroundImgPath[img]}
      fullImg={fullCoverBackground}
    >
      <DialogContainer>
        {textAndTypeArray ? (
          <NPCMultiDialog
            textAndTypeArray={textAndTypeArray}
            onClose={onClose}
          />
        ) : questions && answers ? (
          <QuestionDialog
            questions={questions}
            answers={answers}
            onClose={onClose}
          />
        ) : text && imagePath ? (
          <NPCDialog
            text={text}
            imagePath={imagePath}
            onClose={onClose}
            type={NPCDialogType.TextAndThumbnail}
          />
        ) : (
          <NPCDialog
            text={text}
            onClose={onClose}
            type={NPCDialogType.TextOnly}
          />
        )}
      </DialogContainer>
    </BackgroundContainer>
  );
};

interface IImgContainerProps {
  imgPath: string;
  fullImg: boolean;
}

const BackgroundContainer = styled.div<IImgContainerProps>`
  width: 100%;
  height: 100%;
  background-image: url(${props => props.imgPath});
  background-size: ${props => (props.imgPath ? 'cover' : 'auto')};
  display: flex;
  justify-content: space-evenly;
  align-items: center;
`;

const DialogContainer = styled.div`
  display: flex;
  justify-content: center;
  padding-top: 200px;
`;
