import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import { Oval } from "react-loader-spinner";
import Swal from "sweetalert2";
import UseFullScreenLoader from "../../../../hooks/UseFullScreenLoader";
import { useDeleteJob } from "../../../../utils/hooks";
import { useGetPostedJobs } from "../../../../utils/hooks/useGetPostedJobs";

const JobListingsTable = () => {
  const [getPostedJobs, setPostedJobs] = useState<Job[]>([]);
  const [pageInfo, setPageInfo] = useState<string | null>("/?page=1");
  const [sortOption, setSortOption] = useState<string>("desc");

  const [getLoading, setLoading] = useState<boolean>(false);
  const router = useRouter();
  const FetchPostedJobs = async () => {
    try {
      const { resp, meta } = (await useGetPostedJobs(
        pageInfo,
        sortOption
      )) as PostedJobsResp;
      setPostedJobs([...getPostedJobs, ...resp]);
      setPageInfo(meta?.nextPageUrl);
    } catch (error) {
      console.error("Error fetching POST API (Job Post):", error);
    }
  };

  // delete job handler
  const handleDeleteJob = async (jobId: number) => {
    const result = await Swal.fire({
      title: "Are you sure?",
      text: "You won't be able to revert this!",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, delete it!",
    });
    if (result.isConfirmed) {
      setLoading(true);
      const { resp, status } = (await useDeleteJob(
        jobId
      )) as unknown as DeleteJobResp;
      setLoading(false);
      if (resp.success) {
        const ok = await Swal.fire({
          title: status == 200 ? "Success" : "Failed",
          text: resp.message,
          icon: status == 200 ? "success" : "error",
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Ok",
        });

        if (ok.isConfirmed) {
          router.reload();
        }
      } else {
        await Swal.fire({
          title: status == 200 ? "Success" : "Failed",
          text: resp.message,
          icon: status == 200 ? "success" : "error",
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Ok",
        });
      }
    }
  };

  useEffect(() => {
    if (pageInfo === "/?page=1") {
      FetchPostedJobs();
    }
  }, [pageInfo, getPostedJobs]);
  useEffect(() => {
    FetchPostedJobs();
  }, []);

  let content = (
    <table className="default-table manage-job-table">
      <thead>
        <tr>
          <th>Title</th>
          <th>Published On</th>
          <th>Expired date</th>
          <th>Status</th>
          <th>Action</th>
        </tr>
      </thead>

      <tbody>
        {getPostedJobs.map((item) => (
          <tr key={item.id}>
            <td>
              {/* <!-- Job Block --> */}
              <div className="job-block">
                <div className="inner-box">
                  <div className="content">
                    <span className="company-logo">
                      <img
                        alt={"company logo"}
                        className="thumb"
                        src={
                          item.cmpanyLogoUrl
                            ? item.cmpanyLogoUrl
                            : "/images/human_capital_logo.png"
                        }
                        width={50}
                        height={50}
                        onError={(e: any) => {
                          e.target.src = "/images/human_capital_logo.png";
                          e.target.onerror = null;
                        }}
                      />
                    </span>
                    <h4>
                      <Link href={`/dashboard/manage-jobs/${item.id}`}>
                        {item.title}
                      </Link>
                    </h4>
                    <ul className="job-info">
                      <li onClick={() => console.log(item)}>
                        <span className="icon flaticon-briefcase"></span>
                        {item?.company?.name}
                      </li>
                      <li>
                        <span className="icon flaticon-map-locator"></span>
                        {item.location}
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </td>

            <td>{item.openingDate} </td>
            <td>{item.closingDate}</td>
            <td className="status">
              {!item.isDraft ? (
                "Published"
              ) : (
                <span className="text-warning">Draft</span>
              )}
            </td>
            <td>
              <div className="option-box">
                <ul className="option-list">
                  <li>
                    <Link
                      href={`/dashboard/manage-jobs/${item.id}`}
                      data-text="View Job"
                    >
                      <span className="la la-eye"></span>
                    </Link>
                  </li>
                  <li>
                    <Link
                      href={`/dashboard/manage-jobs/${item.id}/edit`}
                      data-text="Edit Job"
                    >
                      <span className="la la-pencil"></span>
                    </Link>
                  </li>
                  <li>
                    <button
                      data-text="Delete Job"
                      onClick={() => handleDeleteJob(item.id as number)}
                    >
                      <span className="la la-trash"></span>
                    </button>
                  </li>
                </ul>
              </div>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );

  return (
    <>
      {getLoading && <UseFullScreenLoader text="Please wait..." />}
      <div className="tabs-box">
        <div className="widget-title">
          <h4>My Job Listings</h4>

          <div className="chosen-outer">
            {/* <!--Tabs Box--> */}
            <select
              onChange={(e) => {
                setSortOption(e.target.value);
                setPageInfo("/?page=1");
                setPostedJobs([]);
                FetchPostedJobs();
              }}
              className="chosen-single form-select"
            >
              <option value={"desc"}>Newest</option>
              <option value={"asc"}>Oldest</option>
            </select>
          </div>
        </div>
        {/* End filter top bar */}

        {/* Start table widget content */}
        <div className="widget-content">
          <div className="table-outer">
            <InfiniteScroll
              dataLength={getPostedJobs!.length}
              next={FetchPostedJobs}
              hasMore={pageInfo !== null}
              loader={
                <div className="d-flex justify-content-center py-4">
                  <Oval
                    visible={true}
                    height="40"
                    width="40"
                    color="#055875"
                    secondaryColor="#055875c2"
                    ariaLabel="oval-loading"
                  />
                </div>
              }
              endMessage={
                <p style={{ textAlign: "center" }}>
                  <b>Yay! You have seen it all</b>
                </p>
              }
            >
              {content}
            </InfiniteScroll>
          </div>
        </div>
        {/* End table widget content */}
      </div>
    </>
  );
};

export default JobListingsTable;
