import React, { useState } from "react";

import PaginatedList from "../../Pagination/PaginatedList";
import { handlePagingFunc } from "../../Pagination/HandlePagination";
import { PriceFormatter } from "../../Helpers/PriceFormatter";

function CouponTable({ coupon }) {
  const [currentPage, setCurrentPage] = useState(0);
  const indexOfFirstItem = Number(currentPage);
  const indexOfLastItem =
    Number(indexOfFirstItem) + Number(process.env.REACT_APP_ITEM_PER_PAGE);
  const currentCoupon = coupon?.data?.slice(indexOfFirstItem, indexOfLastItem);

  const handlePagination = (e) => {
    handlePagingFunc(e, setCurrentPage);
  };

  return (
    <div className="flex flex-col justify-between h-full">
      <table className="wallet-activity w-full table-auto border-collapse text-left">
        <thead className="border-b-2">
          <tr className="text-slate-600">
            <th className="p-2">Date</th>
            <th className="p-2">Description</th>
            <th className="p-2">Amount</th>
            <th className="p-2">Active</th>
          </tr>
        </thead>
        {coupon.data.length ? (
          <tbody>
            {currentCoupon.map((item, index) => {
              let thePrice = PriceFormatter(
                item?.price * 0.01,
                item?.currency_code,
                item?.currency
              );
              return (
                <tr key={index} className="text-slate-500">
                  <td className="p-2">{item.added}</td>
                  <td className="p-2">{item.code}</td>
                  <td className="p-2">{item.amount}</td>
                  <td className="p-2">{item.status}</td>
                </tr>
              );
            })}
          </tbody>
        ) : coupon.error ? (
          <tbody>
            <tr className="text-slate-500">
              <td className="p-2" colSpan={4}>
                Opps! an error occurred. Please try again!
              </td>
            </tr>
          </tbody>
        ) : (
          <tbody>
            <tr className="text-slate-500">
              <td className="p-2" colSpan={4}>
                No Purchase History Found!
              </td>
            </tr>
          </tbody>
        )}
      </table>

      {/* PAGINATION BUTTON */}
      <PaginatedList
        onClick={handlePagination}
        prev={currentPage == 0 ? true : false}
        next={
          currentPage + Number(process.env.REACT_APP_ITEM_PER_PAGE) >=
          coupon?.data?.length
            ? true
            : false
        }
        data={coupon?.data}
        start={indexOfFirstItem}
        stop={indexOfLastItem}
      />
      {/* END OF PAGINATION BUTTON */}
    </div>
  );
}

export default CouponTable;
