import React, { useEffect, useState } from 'react';
import Draggable from 'react-draggable';
import styled from 'styled-components';
import { uiFonts } from '../../constants/uiFonts';
import SelectArrow from '../Arrow/SelectArrow';
import Book from './img/0.png';

export interface IStaticBookProps {
  content: string;
  onChange?: (slice: string) => void;
  onClose?: () => void;
}

export const StaticBook: React.FC<IStaticBookProps> = ({
  content,
  onChange,
  onClose,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  // create slicedContent with string sliced every 550 characters
  const slicedContent = content.match(/.{1,550}/g) || [];

  useEffect(() => {
    if (onChange) onChange(slicedContent[currentIndex]);
  }, [currentIndex]);

  const bookLength = slicedContent.length - 1;

  const onLeftClick = () => {
    if (currentIndex === 0) setCurrentIndex(bookLength);
    else setCurrentIndex(index => index - 1);
  };
  const onRightClick = () => {
    if (currentIndex === bookLength) setCurrentIndex(0);
    else setCurrentIndex(index => index + 1);
  };

  const getCurrentContentSlice = () => {
    return slicedContent[currentIndex];
  };

  return (
    <Draggable>
      <Container>
        <CloseButton onPointerDown={onClose}>X</CloseButton>
        <ColumnBook isLastPage={currentIndex === bookLength}>
          {getCurrentContentSlice()}
        </ColumnBook>

        <ArrowContainer>
          {currentIndex >= 1 && (
            <SelectArrow
              direction="left"
              onPointerDown={onLeftClick}
            ></SelectArrow>
          )}
          {currentIndex !== bookLength && (
            <SelectArrow
              direction="right"
              onPointerDown={onRightClick}
            ></SelectArrow>
          )}
        </ArrowContainer>
      </Container>
    </Draggable>
  );
};

const Container = styled.div`
  background-image: url(${Book});
  background-repeat: no-repeat;
  position: relative;
  width: 778px;
  height: 463px;
  background-position-y: -1rem;
`;

const CloseButton = styled.p`
  position: absolute;
  top: 1.9rem;
  right: 5rem;
  font-size: ${uiFonts.size.large} !important;
`;

interface IColumnBook {
  isLastPage: boolean;
}

const ColumnBook = styled.span<IColumnBook>`
  position: absolute;
  left: 5.2rem;
  top: 3.8rem;
  width: ${({ isLastPage }) => (!isLastPage ? '77%' : '37%')};
  column-count: ${({ isLastPage }) => (isLastPage ? 1 : 2)};
  grid-gap: 56px;
  min-height: 340px;
`;
const ArrowContainer = styled.span`
  display: flex;
  height: 100%;
  align-items: center;
`;
