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

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

type Props = {
  defaultPage?: number;
  total?: number;
  onChange: (page: number) => void;
};

const Pagination: React.FunctionComponent<Props> = ({
  defaultPage = 1,
  total = 1,
  onChange,
}) => {
  const [currentPage, setPage] = useState(defaultPage);
  const inputRef = useRef(null);
  const handleRightClick = () => {
    const nextPage = currentPage + 1;
    
    if (nextPage <= total) {
      setPage(nextPage);
      onChange(nextPage);
    }
  };

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPage(parseInt(e.target.value) || 0);
  };

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

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

export default Pagination;
