import React, { useCallback, useEffect, useMemo, useState } from "react";
import dataImage1 from "../../assets/images/data-table-user-1.png";

import PaginatedList from "../Pagination/PaginatedList";
import { handlePagingFunc } from "../Pagination/HandlePagination";
import usersService from "../../services/UsersService";
import LoadingSpinner from "../Spinners/LoadingSpinner";

import {useNavigate, useLocation} from 'react-router-dom'

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

  const [tasksData, setTasksData] = useState(null);
  const [loader, setLoader] = useState(true);

  let apiCall = useMemo(() => new usersService(), []);

  const displayTasks = useCallback(async () => {
    try {
      const res = await apiCall.getMyActiveTaskList();
      let {
        data: { result_list },
        internal_return,
        statusText,
      } = await res;
      if (internal_return < 0 || statusText !== "OK") return;
      setTasksData(result_list);
      setLoader(false);
    } catch (error) {
      throw new Error(error);
    }
  }, [apiCall]);

  useEffect(() => {
    displayTasks();
  }, []);

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

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

  return (
    <div
      className={`update-table w-full p-8 bg-white dark:bg-dark-white   overflow-hidden rounded-2xl section-shadow min-h-[520px] ${
        className || ""
      }`}
    >
      {loader ? (
        <div className="w-full h-[500px] flex items-center justify-center">
          <LoadingSpinner size="16" color="sky-blue" />
        </div>
      ) : (
        <div className="relative w-full overflow-x-auto sm:rounded-lg">
          <div className="overflow-y-auto h-auto w-full">
            {tasksData?.length > 0 ? (
              currentTask?.map((task, idx) => (
                <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">
                    <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 whitespace-nowrap">
                          {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">
                            {Number(task?.price) * 0.01}
                          </span>
                        </span>
                        <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 className="text-right 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>
              ))
            ) : (
              <div className="font-bold text-xl text-dark-gray dark:text-white whitespace-nowrap">
                <div className="p-2">
                  No Tasks!
                </div>
              </div>
            )}
          </div>

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

/* */
