import { useState } from "react";
import dataImage1 from "../../assets/images/data-table-user-1.png";
import PaginatedList from "../Pagination/PaginatedList";
import { handlePagingFunc } from "../Pagination/HandlePagination";
import LoadingSpinner from "../Spinners/LoadingSpinner";
import { useNavigate, useLocation } from "react-router-dom";
import { PriceFormatter } from "../Helpers/PriceFormatter";

const noTasksBg = require("../../assets/images/no-task-background.jpg");

export default function MyJobTable({ className, ActiveJobList }) {
  let navigate = useNavigate();
  let { pathname } = useLocation();

  const [currentPage, setCurrentPage] = useState(0);
  const indexOfFirstItem = Number(currentPage);
  const indexOfLastItem =
    Number(indexOfFirstItem) + Number(process.env.REACT_APP_ITEM_PER_PAGE);
  const currentTask = ActiveJobList?.data?.slice(
    indexOfFirstItem,
    indexOfLastItem
  );

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

  // To navigate to task
  const [btnLoader, setBtnLoader] = useState(false);
  const navigateMarket = () => {
    setBtnLoader(true);
    setTimeout(() => {
      navigate("/market", { replace: true });
      setBtnLoader(false);
    }, 2500);
  };

  return (
    <div
      className={`update-table w-full p-8 bg-white dark:bg-dark-white overflow-hidden rounded-2xl section-shadow min-h-[520px] relative ${
        className || ""
      } bg-cover bg-center`}
      style={{
        backgroundImage: !ActiveJobList?.data.length
          ? `url('${noTasksBg}')`
          : "none",
      }}
    >
      {/* Adding this dark overlay in order to see the texts properly */}
      {!ActiveJobList?.data.length && (
        <div class="absolute inset-0 bg-black opacity-30"></div>
      )}
      {ActiveJobList?.data.length > 0 && ActiveJobList.loading && (
        <div className="w-full h-[520px] flex items-center justify-center">
          <LoadingSpinner size="16" color="sky-blue" />
        </div>
      )}

      <div className="relative w-full sm:rounded-lg">
        <div className="h-auto w-full">
          {ActiveJobList?.data?.length > 0 &&
            currentTask?.map((task, idx) => {
              let thePrice = PriceFormatter(
                task?.price * 0.01,
                task?.currency_code,
                task?.currency
              );
              return (
                <div
                  className="bg-white dark:bg-dark-white border-b dark:border-[#5356fb29] w-full flex justify-between items-center hover:bg-gray-50"
                  key={idx}
                >
                  <div className="py-4 max-w-[80%]">
                    <div className="flex space-x-2 items-center">
                      <div className="w-full min-w-[60px] max-w-[60px] flex-[0.1] h-[60px] rounded-full overflow-hidden flex justify-center items-center">
                        <img
                          src={dataImage1}
                          alt="data"
                          className="w-full h-full"
                        />
                      </div>
                      <div className="flex flex-col flex-[0.9]">
                        <h1 className="font-bold text-xl text-dark-gray dark:text-white">
                          {task?.title}
                        </h1>
                        <span className="text-base text-gray-600">
                          {task?.description}
                        </span>
                        <span className="text-sm text-thin-light-gray">
                          Price:
                          <span className="text-purple ml-1">{thePrice}</span>
                        </span>
                        <div className="flex gap-4 items-center">
                          <span className="text-sm text-thin-light-gray">
                            Duration:
                            <span className="text-purple ml-1">
                              {Number(task?.timeline_days) === 1
                                ? `${task?.timeline_days} day`
                                : `${task?.timeline_days} day(s)`}
                            </span>
                          </span>
                          <span className="text-sm text-thin-light-gray">
                            Due Date:
                            <span className="text-purple ml-1">
                              {task?.delivery_date}
                            </span>
                          </span>
                          <span className="text-sm text-thin-light-gray">
                            Confirmation:
                            <span className="text-purple ml-1">
                              {task?.contract}
                            </span>
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="flex justify-center items-center py-4 px-2">
                    <button
                      type="button"
                      onClick={() => {
                        navigate("/manage-active-job", {
                          state: { ...task, pathname },
                        });
                      }}
                      className="w-20 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                    >
                      Manage
                    </button>
                  </div>
                </div>
              );
            })}

          {ActiveJobList?.data?.length <= 0 && (
            <div className="flex flex-col items-center justify-center gap-9 my-5">
              <div className="p-2 font-bold text-3xl text-white whitespace-nowrap">
                You currently have "0" task
              </div>
              <button
                className="w-[115px] h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                onClick={navigateMarket}
              >
                {btnLoader ? (
                  <div className="signup btn-loader"></div>
                ) : (
                  "Find Task"
                )}
              </button>
            </div>
          )}
          {ActiveJobList?.internal_return < 0 && (
            <div className="font-bold text-xl text-dark-gray dark:text-white whitespace-nowrap">
              <p className="p-2">Error Occurred! Unable to display Tasks!</p>
            </div>
          )}
        </div>

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