import React, { useMemo, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import Icons from "../../Helpers/Icons";
import { PriceFormatter } from "../../Helpers/PriceFormatter";
import { handlePagingFunc } from "../../Pagination/HandlePagination";
import PaginatedList from "../../Pagination/PaginatedList";
import LoadingSpinner from "../../Spinners/LoadingSpinner";

export default function FamilyNewTasks({
  familyData,
  className,
  action,
}) {
  let navigate = useNavigate();
  let { pathname } = useLocation();

  // ...
  let filteredFamilyData = useMemo(
    () => familyData?.data?.result_list?.filter((data) => data.family_uid !== ""),
    [familyData?.data?.result_list]
  );

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

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

  return (
    <div
      className={`update-table w-full bg-white dark:bg-dark-white h-full lg:min-h-[538px] overflow-hidden rounded-2xl section-shadow p-3 ${
        familyData?.data?.result_list?.length <= 0 && "flex items-center justify-center"
      }`}
    >
      {familyData.loading ? (
        <div className="w-full h-full flex justify-center items-center">
          <LoadingSpinner size={16} color="sky-blue" height='h-[30rem]' />
        </div>
      ) : (
        <>
          {familyData?.data?.result_list && (
            <div className="relative w-full overflow-x-auto sm:rounded-lg flex flex-col justify-between h-full">
              <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                <tbody>
                  {
                    <>
                      {familyData?.data?.result_list?.length <= 0 ? (
                        <tr>
                          <td
                            colSpan="2"
                            className="text-center py-4 font-bold text-xl text-dark-gray dark:text-white whitespace-nowrap flex items-center justify-center gap-1"
                          >
                            You currently have no active tasks{" "}
                            <span
                              className="text-blue-400 cursor-pointer hover:underline transition duration-150"
                              onClick={action}
                            >
                              add new
                            </span>
                          </td>
                        </tr>
                      ) : (
                        currentTasks.map((value, index) => {
                          // find due date
                          const dueDate = value?.delivery_date.split(" ")[0];
                          // the price
                          let thePrice = PriceFormatter(
                            value?.price * 0.01,
                            value?.currency_code,
                            value?.currency
                          );
                          let image = `${familyData?.data?.result_list}${localStorage.getItem(
                            "session_token"
                          )}/job/${value.job_uid}`;
                          return (
                            <tr
                              key={index}
                              className="bg-white dark:bg-dark-white border-b dark:border-[#5356fb29] hover:bg-gray-50"
                            >
                              <td className=" py-4">
                                <div className="flex space-x-2 items-center w-full">
                                  <div className="w-[60px] h-[60px] p-2 bg-alice-blue rounded-full overflow-hidden flex justify-center items-center">
                                    <img
                                      src={image}
                                      alt="data"
                                      className="w-full h-full rounded-full"
                                    />
                                  </div>
                                  <div className="flex flex-col flex-[0.9]">
                                    <h1 className="font-bold text-xl text-dark-gray dark:text-white">
                                      {value.title}
                                    </h1>
                                    <div className="flex flex-col sm:flex-row items-start gap-1 md:gap-4 md:items-center">
                                      <span className="text-sm text-thin-light-gray flex flex-start gap-1">
                                      Reward:{" "}
                                        <span className="text-purple">
                                          {thePrice}
                                        </span>
                                      </span>
                                      <span className="text-sm text-thin-light-gray">
                                        Duration:{" "}
                                        <span className="text-purple">
                                          {" "}
                                          {value.timeline_days} day(s)
                                        </span>
                                      </span>
                                      <span className="text-sm text-thin-light-gray">
                                        Due Date:{" "}
                                        <span className="text-purple">
                                          {" "}
                                          {dueDate}
                                        </span>
                                      </span>
                                    </div>
                                  </div>
                                </div>
                              </td>

                              <td className="text-right py-4 px-2">
                                <button
                                  type="button"
                                  onClick={() => {
                                    navigate("/manage-active-job", {
                                      state: {
                                        ...value,
                                        pathname,
                                      },
                                    });
                                  }}
                                  className="w-20 h-11 flex justify-center items-center btn-gradient text-base rounded-full text-white"
                                >
                                  <Icons name="right-arrow" />
                                </button>
                              </td>
                            </tr>
                          );
                        })
                      )}
                    </>
                  }
                </tbody>
              </table>
              {/* PAGINATION BUTTON */}
              <PaginatedList
                onClick={handlePagination}
                prev={currentPage == 0 ? true : false}
                next={
                  currentPage + Number(process.env.REACT_APP_ITEM_PER_PAGE) >=
                  filteredFamilyData?.length
                    ? true
                    : false
                }
                data={filteredFamilyData}
                start={indexOfFirstItem}
                stop={indexOfLastItem}
              />
              {/* END OF PAGINATION BUTTON */}
            </div>
          )}
        </>
      )}
    </div>
  );
}
