import React, { useCallback, useEffect, useMemo, useState } from "react";
import dataImage1 from "../../assets/images/data-table-user-1.png";
import dataImage2 from "../../assets/images/data-table-user-2.png";
import dataImage3 from "../../assets/images/data-table-user-3.png";
import dataImage4 from "../../assets/images/data-table-user-4.png";
import SelectBox from "../Helpers/SelectBox";
import JobListPopout from "../jobPopout/JobListPopout";
import DeleteJobPopout from "../jobPopout/DeleteJobPopout";

import LoadingSpinner from "../Spinners/LoadingSpinner";

import PaginatedList from "../Pagination/PaginatedList";
import { handlePagingFunc } from "../Pagination/HandlePagination";
import EditJobPopOut from "../jobPopout/EditJobPopout";
import usersService from "../../services/UsersService";
import { useSelector } from "react-redux";

export default function MyJobTable({ MyJobList, reloadJobList, className }) {
  const [myCountry, setCountries] = useState("");
  const {
    userDetails: { country },
  } = useSelector((state) => state?.userDetails);

  const userApi = useMemo(() => new usersService(), []);

  // Get Country Api
  const getCountryList = useCallback(async () => {
    const res = await userApi.getSignupCountryData();

    try {
      if (res.status === 200) {
        const {
          data: { signup_country },
        } = await res;
        console.log(signup_country);
        let checkCountry = signup_country
          ?.filter((item) => item[0] == country)
          ?.map((item, idx) => item[1])
          .join("");
        setCountries(checkCountry);
      }
    } catch (error) {
      throw new Error(error);
    }
  }, [userApi, country]);

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

  const filterCategories = ["All Categories", "Explore", "Featured"];
  const [selectedCategory, setCategory] = useState(filterCategories[0]);

  let [jobPopout, setJobPopout] = useState({ show: false, data: {} }); // STATE TO HOLD THE VALUE OF THE ALERT DETAILS AND DETERMINE WHEN TO SHOW

  let [deleteJobPopout, setDeleteJobPopout] = useState({
    show: false,
    data: {},
  }); // STATE TO HOLD THE VALUE OF THE ITEM DETAILS TO DELETE AND DETERMINE WHEN TO SHOW
  const [editJob, setEditJob] = useState({ show: false, data: {} });

  const [currentPage, setCurrentPage] = useState(0);
  const indexOfFirstItem = Number(currentPage);
  const indexOfLastItem =
    Number(indexOfFirstItem) + Number(process.env.REACT_APP_ITEM_PER_PAGE);
  const currentJobList = MyJobList?.data?.result_list?.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 ${
        className || ""
      }`}
    >
      <div className="header w-full flex justify-between items-center mb-5">
        <div className="flex space-x-2 items-center">
          <h1 className="text-xl font-bold text-dark-gray dark:text-white tracking-wide">
            All Jobs
          </h1>
        </div>
        <SelectBox
          action={setCategory}
          datas={filterCategories}
          className="Update-table-dropdown"
          contentBodyClasses="w-auto min-w-max"
        />
      </div>
      {MyJobList.loading ? 
      <LoadingSpinner size='16' color='sky-blue' />
      :
      (
        <div className="relative w-full overflow-x-auto sm:rounded-lg flex flex-col justify-between h-full">
          <table className="table-auto min-w-full text-sm text-left text-gray-500 dark:text-gray-400">
            <tbody>
              <tr className="text-base text-thin-light-gray border-b  default-border-b dark:border-[#5356fb29] ottom ">
                <td className="py-1">.</td>
                <td className="py-1 text-right">.</td>
              </tr>

              {selectedCategory === "All Categories" ? (
                <>
                  {MyJobList &&
                    MyJobList?.data?.result_list &&
                    MyJobList.data?.result_list.length > 0 &&
                    currentJobList.map((value, index) => (
                      <tr
                        key={index}
                        className="bg-white dark:bg-dark-white   border-b dark:border-[#5356fb29]  hover:bg-gray-50"
                      >
                        <td className="py-9">
                          <div className="sm:flex sm:space-x-2 sm:justify-between sm:items-center job-items">
                            <div className="flex space-x-2 items-center job-items">
                              <div className="w-[60px] h-[60px] rounded-full overflow-hidden flex justify-center items-center">
                                <img
                                  src={dataImage2}
                                  alt="data"
                                  className="w-full h-full"
                                />
                              </div>
                              <div className="flex flex-col">
                                <h1 className="font-bold text-xl text-dark-gray dark:text-white">
                                  {value.title}
                                </h1>
                                <div>{value.description}</div>
                                <span className="text-sm text-thin-light-gray">
                                  Price:{" "}
                                  <span className="text-purple">
                                    {value.price * 0.01}
                                  </span>
                                </span>
                                <span className="text-sm text-thin-light-gray">
                                  Duration:{" "}
                                  <span className="text-purple">
                                    {" "}
                                    {value.timeline_days} day(s)
                                  </span>
                                </span>
                              </div>
                            </div>

                            <div className="min-w-[110px] max-w-[110px] bg-yellow-300 mx-2 rounded-md flex flex-nowrap space-x-2 justify-center items-center self-end">
                              <button
                                type="button"
                                className="p-2 w-[60px] h-11"
                                onClick={() => {
                                  setDeleteJobPopout({
                                    show: true,
                                    data: value,
                                  });
                                }}
                              >
                                [Delete]
                              </button>
                              <span>|</span>
                              <button
                                type="button"
                                className="p-2 w-[40px] h-11"
                                onClick={() => {
                                  setEditJob({
                                    show: true,
                                    data: value,
                                  });
                                }}
                              >
                                Edit
                              </button>
                            </div>
                          </div>
                        </td>

                        <td className="text-right py-9 px-2">
                          <button
                            type="button"
                            onClick={() => {
                              setJobPopout({ show: true, data: value });
                            }}
                            className="w-20 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                          >
                            Manage
                          </button>
                        </td>
                      </tr>
                    ))}
                </>
              ) : selectedCategory === "Explore" ? (
                <></>
              ) : (
                <></>
              )}
            </tbody>
          </table>

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

      {/* Job List Popout */}
      {jobPopout.show && (
        <JobListPopout
          details={jobPopout.data}
          onClose={() => {
            setJobPopout({ show: false, data: {} });
          }}
          situation={jobPopout.show}
        />
      )}
      {/* End of Job List Popout */}

      {/* Delete Job Popout */}
      {deleteJobPopout.show && (
        <DeleteJobPopout
          details={deleteJobPopout.data}
          onClose={() => {
            setDeleteJobPopout({ show: false, data: {} });
          }}
          reloadJobList={reloadJobList}
          situation={deleteJobPopout.show}
        />
      )}
      {/* END of Delete Job Popout */}

      {editJob.show && (
        <EditJobPopOut
          details={editJob.data}
          onClose={() => {
            setEditJob({
              show: false,
              data: {},
            });
          }}
          situation={editJob.show}
          country={myCountry}
        />
      )}
    </div>
  );
}
