/* eslint-disable max-len */
import React, { useState, useEffect } from "react";
import { ChevronLeftIcon, ChevronRightIcon } from "../../svg";

interface IProps {
  total: number;
  pageSize: number;
  onChange: (page: number) => void;
  changePage?: number;
}

export const Pagination = (props: IProps) => {
  const { total, pageSize, onChange, changePage } = props;

  const [currectPage, setCurrectPage] = useState(1);

  useEffect(() => {
    if (changePage !== undefined) {
      setCurrectPage(changePage);
    }
  }, [changePage]);

  const calculateCount = () => {
    let count = 1;
    if (total > pageSize && !!(total % pageSize)) {
      count = Math.floor(total / pageSize) + 1;
    } else if (total > pageSize && !(total % pageSize)) {
      count = Math.floor(total / pageSize);
    }
    return count;
  };
  const pageCount = calculateCount();

  const handleNext = () => {
    onChange(currectPage + 1);
    setCurrectPage(currectPage + 1);
  };

  const handlePrev = () => {
    onChange(currectPage - 1);
    setCurrectPage(currectPage - 1);
  };

  const keys = Array.from(Array(pageCount).keys());
  const pageList = [...keys];

  return (
    <div className="pagination flex items-center w-fit bg-white drop-shadow-[0px_2px_3px_rgba(0,0,0,0.07)] rounded-[4px] overflow-hidden">
      <button
        disabled={!pageList[currectPage]}
        onClick={handlePrev}
        className="btn bg-transparent hover:bg-transparent p-[10px] text-xs disabled:bg-transparent"
      >
        <ChevronLeftIcon
          className={`w-3 h-3 stroke-base-200 ${
            !pageList[currectPage] ? "stroke-gray-300" : ""
          }`}
        />
      </button>
      <button className="btn bg-transparent hover:bg-transparent py-[10px] px-3 text-base-content">
        {currectPage + 1}
      </button>
      <button
        disabled={!pageList[currectPage + 1]}
        onClick={handleNext}
        className="btn bg-transparent hover:bg-transparent p-[10px] text-xs disabled:bg-transparent"
      >
        <ChevronRightIcon
          className={`w-3 h-3 stroke-base-200 ${
            !pageList[currectPage + 1] ? "stroke-gray-300" : ""
          }`}
        />
      </button>
    </div>
  );
};
export default Pagination;
