import React, { useRef, useEffect, useState } from 'react';

import { Wrapper, Text, Input, ArrowButton } from './styled';

type Props = {
  currentPage: number;
  totalPage: number;
  onChange: (page: number) => void;
};

const Pagination: React.FunctionComponent<Props> = ({
  currentPage = 1,
  totalPage = 1,
  onChange,
}) => {
  const inputRef = useRef(null);
  const [inputValue, setInputValue] = useState(currentPage);

  const handleRightClick = () => {
    const nextPage = currentPage + 1;
    
    if (nextPage <= totalPage) {
      onChange(nextPage);
    }
  };

  const handleLeftClick = () => {
    const prevPage = currentPage - 1;
    
    if (prevPage > 0) {
      onChange(prevPage);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const page = parseInt(e.target.value) || 0;
    
    if (page >= 0 && page <= totalPage) {
      setInputValue(page);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.keyCode === 13) {
      onChange(inputValue);
    }
  }

  useEffect(() => {
    setInputValue(currentPage);
  }, [currentPage]);

  return (
    <Wrapper>
      <Text>Page</Text>
      <ArrowButton onClick={handleLeftClick} variant="left" />
      <Input
        type="tel"
        ref={inputRef}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        value={inputValue}
      />
      <ArrowButton onClick={handleRightClick} variant="right" />
      <Text>of {totalPage}</Text>
    </Wrapper>
  );
};

export default Pagination;
