import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import Link from "next/link";
import { useGetApplicants } from "../../../../utils/hooks/useGetApplicants";
import {
  Dispatch,
  SetStateAction,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import UseFullScreenLoader from "../../../../hooks/UseFullScreenLoader";
import { useApproveApplicant } from "../../../../utils/hooks/useApplicantStatusChange";
import { useRouter } from "next/navigation";
import InfiniteScroll from "react-infinite-scroll-component";
import { Oval } from "react-loader-spinner";
import GuarantorCommunicationModal from "../shortlisted-resumes/GuarantorCommunicationModal";
import Swal from "sweetalert2";
import { useGetInterviews } from "../../../../utils/hooks/useGetInterviews";
import { InterviewData, InterviewsResp } from "../../../..";
import {
  useGetInterviewFeedback,
  useStoreInterviewFeedback,
} from "../../../../utils/hooks/useInterviewFeedback";
import { useSkillApi } from "../../../../utils/hooks/useSkillApi";
import InterviewFeedbackForm, {
  defaultInterviewFeedback,
  InterviewFeedbackPayload,
} from "../../common/interview-feedback/InterviewFeedbackForm";

type ApplicantStatus = "Approved" | "Rejected" | "Shortlisted";

interface InterviewFeedbackModalProps {
  index: number;
  name: string;
  interviewId?: number | string;
  interviewStatus?: string;
  fallbackFeedback?: {
    workStandard?: number;
    errorFreeness?: number;
    helpToImprove?: number;
    communicationSkill?: number;
    listeningSkill?: number;
    informationSharing?: number;
    remarks?: string;
  } | null;
}

const InterviewFeedbackModal = ({
  candidateData,
  onClose,
}: {
  candidateData: {
    name: string;
    interviewId?: number | string;
    interviewStatus?: string;
    fallbackFeedback?: InterviewFeedbackModalProps["fallbackFeedback"];
  } | null;
  onClose?: () => void;
}) => {
  const [feedback, setFeedback] = useState<InterviewFeedbackPayload>(
    defaultInterviewFeedback,
  );
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");

  const normalizedInterviewId = Number(candidateData?.interviewId);
  const hasValidInterviewId =
    Number.isFinite(normalizedInterviewId) && normalizedInterviewId > 0;
  const normalizedInterviewStatus = String(candidateData?.interviewStatus || "")
    .trim()
    .toLowerCase();
  const isInterviewFinished =
    normalizedInterviewStatus.includes("finish") ||
    normalizedInterviewStatus.includes("complete");

  // Fetch feedback whenever the modal opens for a candidate
  useEffect(() => {
    if (!candidateData) return;
    const interviewId = Number(candidateData.interviewId);
    if (!Number.isFinite(interviewId) || interviewId <= 0) return;

    let cancelled = false;

    const doFetch = async () => {
      try {
        setLoading(true);
        setMessage("");
        setFeedback(defaultInterviewFeedback);
        const { resp } = (await useGetInterviewFeedback(interviewId)) as any;
        if (cancelled) return;
        if (resp?.feedback) {
          setFeedback({
            workStandard: resp.feedback.workStandard ?? null,
            errorFreeness: resp.feedback.errorFreeness ?? null,
            helpToImprove: resp.feedback.helpToImprove ?? null,
            communicationSkill: resp.feedback.communicationSkill ?? null,
            listeningSkill: resp.feedback.listeningSkill ?? null,
            informationSharing: resp.feedback.informationSharing ?? null,
            remarks: resp.feedback.remarks ?? "",
          });
        } else if (candidateData.fallbackFeedback) {
          setFeedback({
            workStandard: candidateData.fallbackFeedback.workStandard ?? null,
            errorFreeness: candidateData.fallbackFeedback.errorFreeness ?? null,
            helpToImprove: candidateData.fallbackFeedback.helpToImprove ?? null,
            communicationSkill:
              candidateData.fallbackFeedback.communicationSkill ?? null,
            listeningSkill:
              candidateData.fallbackFeedback.listeningSkill ?? null,
            informationSharing:
              candidateData.fallbackFeedback.informationSharing ?? null,
            remarks: candidateData.fallbackFeedback.remarks ?? "",
          });
        } else {
          setFeedback(defaultInterviewFeedback);
        }
      } catch (error) {
        if (cancelled) return;
        console.error("Error loading interview feedback:", error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    doFetch();
    return () => {
      cancelled = true;
    };
  }, [candidateData]);

  const onChangeScore = (
    key: keyof InterviewFeedbackPayload,
    value: number,
  ) => {
    setFeedback((prev) => ({ ...prev, [key]: value }));
  };

  const submitFeedback = async () => {
    const profileType =
      typeof window !== "undefined"
        ? localStorage.getItem("profileType")
        : null;
    if (profileType !== "Company") {
      setMessage("Please login with a company account to submit feedback.");
      return;
    }

    if (!hasValidInterviewId) {
      setMessage("Unable to submit feedback. Interview id is missing.");
      return;
    }

    if (!isInterviewFinished) {
      setMessage("Feedback can be submitted after interview is finished.");
      return;
    }

    if (
      feedback.workStandard === null ||
      feedback.errorFreeness === null ||
      feedback.helpToImprove === null ||
      feedback.communicationSkill === null ||
      feedback.listeningSkill === null ||
      feedback.informationSharing === null
    ) {
      setMessage("Please select one option for all feedback rows.");
      return;
    }

    try {
      setSaving(true);
      setMessage("");
      const payload = {
        workStandard: feedback.workStandard as number,
        errorFreeness: feedback.errorFreeness as number,
        helpToImprove: feedback.helpToImprove as number,
        communicationSkill: feedback.communicationSkill as number,
        listeningSkill: feedback.listeningSkill as number,
        informationSharing: feedback.informationSharing as number,
        remarks: feedback.remarks?.trim() || undefined,
      };

      await useStoreInterviewFeedback(normalizedInterviewId, payload);
      setMessage("Feedback saved successfully.");

      // Auto-close modal after a short delay
      setTimeout(() => {
        const modalEl = document.getElementById("sharedFeedbackModal");
        if (modalEl) {
          const bootstrap = (window as any).bootstrap;
          const modalInstance = bootstrap?.Modal?.getInstance(modalEl);
          if (modalInstance) {
            modalInstance.hide();
          } else {
            const closeBtn = modalEl.querySelector(
              '[data-bs-dismiss="modal"]',
            ) as HTMLElement;
            closeBtn?.click();
          }
        }
        setMessage("");
        onClose?.();
      }, 1000);
    } catch (error) {
      console.error("Error saving interview feedback:", error);
      if ((error as any)?.response?.status === 403) {
        setMessage("Only company accounts can submit interview feedback.");
        return;
      }
      const apiMessage =
        (error as any)?.response?.data?.error ||
        (error as any)?.response?.data?.message ||
        (error as any)?.message ||
        "Failed to save feedback.";
      setMessage(apiMessage);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div
      className="modal fade"
      id="sharedFeedbackModal"
      tabIndex={-1}
      aria-labelledby="sharedFeedbackModalLabel"
      aria-hidden="true"
    >
      <div className="modal-dialog modal-xl">
        <div className="modal-content">
          <div className="modal-header">
            <button
              type="button"
              className="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
              onClick={onClose}
            ></button>
          </div>
          <div className="modal-body">
            {candidateData && (
              <InterviewFeedbackForm
                feedback={feedback}
                mode="company"
                title="Interview Feedback"
                subtitle={`For Evaluating ${candidateData.name}`}
                radioGroupPrefix="shared"
                disabled={loading || saving}
                message={message}
                remarksPlaceholder="Add remarks ..."
                onScoreChange={onChangeScore}
                onRemarksChange={(value) =>
                  setFeedback((prev) => ({
                    ...prev,
                    remarks: value,
                  }))
                }
              />
            )}
          </div>
          <div className="modal-footer">
            <button
              type="button"
              className="theme-btn btn-style-one"
              disabled={saving || loading}
              onClick={submitFeedback}
            >
              {saving ? "Saving..." : "Submit"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const WidgetContentBox = ({
  jobId,
  sortOption,
  jobTitle,
  setPageInfo,
  pageInfo,
}: {
  jobId: number;
  sortOption: string;
  jobTitle: string;
  setPageInfo: Dispatch<SetStateAction<string | null>>;
  pageInfo: string | null;
}) => {
  const router = useRouter();
  const skillApiInstance = useSkillApi() as any;
  const skillApiRef = useRef(skillApiInstance);
  skillApiRef.current = skillApiInstance;
  const dataLoadedRef = useRef(false);
  const [getIsLoading, setIsLoading] = useState(false);
  const [getApplicants, setApplicants] = useState<JobApplication[]>([]);
  const [getTotalApplicants, setTotalApplicants] = useState<Number>(0);
  const [getApproveCount, setApproveCount] = useState<Number>(0);
  const [getRejectCount, setRejectCount] = useState<Number>(0);
  const [getPendingCount, setPendingCount] = useState<Number>(0);
  const [getShortlistCount, setShortlistCount] = useState<Number>(0);
  const [interviewLookup, setInterviewLookup] = useState<
    Record<
      string,
      {
        id: number;
        status: string;
        score: number;
        feedback?: {
          workStandard?: number;
          errorFreeness?: number;
          helpToImprove?: number;
          communicationSkill?: number;
          listeningSkill?: number;
          informationSharing?: number;
          remarks?: string;
        } | null;
      }
    >
  >({});
  const [attachedSkillExamLookup, setAttachedSkillExamLookup] = useState<
    Record<number, Array<{ id: number; name: string }>>
  >({});

  const [isApproveModalOpen, setIsApproveModalOpen] = useState(false);
  const [isRejectModalOpen, setIsRejectModalOpen] = useState(false);
  const [isShortlistModalOpen, setIsShortlistModalOpen] = useState(false);

  // Single shared modal state — only ONE modal rendered outside the loop
  const [activeFeedbackCandidate, setActiveFeedbackCandidate] = useState<{
    name: string;
    interviewId?: number | string;
    interviewStatus?: string;
    fallbackFeedback?: InterviewFeedbackModalProps["fallbackFeedback"];
  } | null>(null);

  const openFeedbackModal = (candidate: JobApplication) => {
    const details = getResolvedInterviewDetailsStable(candidate);
    setActiveFeedbackCandidate({
      name: `${candidate?.candidate?.firstName ?? ""} ${candidate?.candidate?.lastName ?? ""}`.trim(),
      interviewId: details.interviewId,
      interviewStatus: details.meetingStatus,
      fallbackFeedback: details.fallbackFeedback,
    });
  };

  useEffect(() => {
    console.log("getApplicants => ", getApplicants);
    // getApplicants.map((applicant) => {
    //   console.log(
    //     "Applicant data => ",
    //     applicant.candidate.examPerformances?.[0]?.score
    //   );
    // });
  }, [getApplicants]);

  const FetchApplicants = async () => {
    try {
      pageInfo == "/?page=1" && setIsLoading(true);
      const { resp, status } = (await useGetApplicants(
        jobId,
        sortOption,
        pageInfo,
      )) as JobApplicationResp;
      setApplicants([...getApplicants, ...resp.applicants.data]);
      setPageInfo(resp.applicants.meta.nextPageUrl);
      setTotalApplicants(resp.applicants.meta.total);
      setApproveCount(resp.approvedCount);
      setRejectCount(resp.rejectedCount);
      setPendingCount(resp.pendingCount);
      setShortlistCount(resp.shortlistCount);
    } catch (error) {
      console.error("Error fetching GET API (Applicants):", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleStatusChange = async (
    jobId: Number,
    candidateId: Number,
    changedStatus: ApplicantStatus,
  ) => {
    const modalTitleMap: Record<ApplicantStatus, string> = {
      Approved: "Select Applicant?",
      Rejected: "Reject Applicant?",
      Shortlisted: "Shortlist Applicant?",
    };

    const icon: Record<ApplicantStatus, string> = {
      Approved: "success",
      Rejected: "warning",
      Shortlisted: "info",
    };

    const modalIconHtml: Record<ApplicantStatus, string> = {
      Approved: '<i class="fas fa-circle-check text-success fa-2x"></i>',
      Rejected: '<i class="fas fa-circle-xmark text-danger fa-2x"></i>',
      Shortlisted: '<i class="fas fa-star-half-stroke text-warning fa-2x"></i>',
    };

    const res = await Swal.fire({
      title: modalTitleMap[changedStatus],
      // icon: "success",
      // iconHtml: modalIconHtml[changedStatus],
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, Sure!",
      cancelButtonText: "Cancel",
    });
    if (res.isConfirmed) {
      try {
        setIsLoading(true);
        const { status } = (await useApproveApplicant(
          jobId,
          candidateId,
          changedStatus,
        )) as ApplicationUpdateResp;
        FetchApplicants();
      } catch (error) {
        console.error("Error fetching PUT API (Applicants):", error);
      } finally {
        router.refresh();
      }
    }
  };
  const handleViewCV = (fileUrl: string) => {
    // Open a new window with specified settings
    window.open(
      "/cv-viewer?fileUrl=" + encodeURIComponent(fileUrl),
      "_blank",
      "width=800,height=600",
    );
  };

  const loadInterviewsLookup = useCallback(async () => {
    try {
      let nextPage: string | null = "/?page=1";
      let pageCounter = 0;
      const lookup: Record<
        string,
        {
          id: number;
          status: string;
          score: number;
          feedback?: {
            workStandard?: number;
            errorFreeness?: number;
            helpToImprove?: number;
            communicationSkill?: number;
            listeningSkill?: number;
            informationSharing?: number;
            remarks?: string;
          } | null;
        }
      > = {};

      while (nextPage && pageCounter < 20) {
        const { resp } = (await useGetInterviews(nextPage)) as InterviewsResp;
        const interviews = resp?.data || [];

        interviews.forEach((interview: any) => {
          const key = `${interview.jobId}-${interview.candidateId}`;
          const normalizedStatus = String(interview.meetingStatus || "")
            .trim()
            .toLowerCase();
          const isFinishedLike =
            normalizedStatus.includes("finish") ||
            normalizedStatus.includes("complete");
          const hasFeedback = !!interview?.candidateFeedback;
          const rank = hasFeedback ? 3 : isFinishedLike ? 2 : 1;

          const current = lookup[key];
          if (
            !current ||
            rank > current.score ||
            (rank === current.score && Number(interview.id) > current.id)
          ) {
            lookup[key] = {
              id: Number(interview.id),
              status: String(interview.meetingStatus || ""),
              score: rank,
              feedback: interview?.candidateFeedback || null,
            };
          }
        });

        nextPage = resp?.meta?.nextPageUrl || null;
        pageCounter += 1;
      }

      setInterviewLookup(lookup);
    } catch (error) {
      console.error("Error fetching GET API (Interviews):", error);
    }
  }, []);

  const getResolvedInterviewDetailsStable = (candidate: JobApplication) => {
    const directInterviewId = Number(candidate?.interviewDetails?.id);
    const directStatus = String(
      candidate?.interviewDetails?.meeting_status || "",
    );
    const directInterviewValid =
      Number.isFinite(directInterviewId) && directInterviewId > 0;

    const key = `${candidate?.jobPostId}-${candidate?.candidateId}`;
    const fallback = interviewLookup[key];

    // Prefer the fallback entry when it is known to already have feedback.
    if (fallback?.score === 3) {
      return {
        interviewId: fallback.id,
        meetingStatus: fallback.status,
        fallbackFeedback: fallback.feedback || null,
      };
    }

    if (directInterviewValid) {
      return {
        interviewId: directInterviewId,
        meetingStatus: directStatus,
        fallbackFeedback: fallback?.feedback || null,
      };
    }

    return {
      interviewId: fallback?.id,
      meetingStatus: fallback?.status || directStatus,
      fallbackFeedback: fallback?.feedback || null,
    };
  };

  const isInterviewFeedbackEnabled = (candidate: JobApplication) => {
    const { interviewId, meetingStatus } =
      getResolvedInterviewDetailsStable(candidate);
    const normalizedStatus = String(meetingStatus || "")
      .trim()
      .toLowerCase();
    const normalizedInterviewId = Number(interviewId);

    return (
      Number.isFinite(normalizedInterviewId) &&
      normalizedInterviewId > 0 &&
      (normalizedStatus.includes("finish") ||
        normalizedStatus.includes("complete"))
    );
  };

  const loadAttachedSkillExamLookup = useCallback(async () => {
    try {
      const data: any = await skillApiRef.current.getExams();
      const exams = Array.isArray(data)
        ? data
        : Array.isArray(data?.data)
          ? data.data
          : Array.isArray(data?.exams)
            ? data.exams
            : Array.isArray(data?.skillExams)
              ? data.skillExams
              : [];

      const lookup: Record<number, Array<{ id: number; name: string }>> = {};

      exams.forEach((exam: any) => {
        const examId = Number(exam?.id ?? exam?.examId ?? exam?.exam_id);
        const jobPostId = Number(exam?.jobPostId ?? exam?.job_post_id);
        if (
          !Number.isFinite(examId) ||
          examId <= 0 ||
          !Number.isFinite(jobPostId) ||
          jobPostId <= 0
        ) {
          return;
        }

        if (!lookup[jobPostId]) {
          lookup[jobPostId] = [];
        }

        lookup[jobPostId].push({
          id: examId,
          name: exam?.title || exam?.name || "Exam",
        });
      });

      setAttachedSkillExamLookup(lookup);
    } catch (error) {
      console.error("Error loading attached skill exam lookup:", error);
    }
  }, []);

  const getAttachedExamScoreInfo = (candidate: JobApplication) => {
    const attachedExamsFromCandidate = ((candidate as any)?.jobPost
      ?.skillExams || []) as Array<{
      id?: number;
      examId?: number;
      exam_id?: number;
      skillExamId?: number;
      title?: string;
      name?: string;
    }>;
    const attachedExamsFromLookup =
      attachedSkillExamLookup[Number(candidate?.jobPostId)] || [];

    const attachedExamIdToName = new Map<number, string>();
    attachedExamsFromCandidate.forEach((exam) => {
      const examId = Number(
        exam?.id ?? exam?.examId ?? exam?.exam_id ?? exam?.skillExamId,
      );
      if (Number.isFinite(examId) && examId > 0) {
        attachedExamIdToName.set(examId, exam?.title || exam?.name || "Exam");
      }
    });
    attachedExamsFromLookup.forEach((exam) => {
      if (!attachedExamIdToName.has(exam.id)) {
        attachedExamIdToName.set(exam.id, exam.name || "Exam");
      }
    });

    const standaloneAttachedId = Number(
      (candidate as any)?.jobPost?.skillExamId,
    );
    if (
      Number.isFinite(standaloneAttachedId) &&
      standaloneAttachedId > 0 &&
      !attachedExamIdToName.has(standaloneAttachedId)
    ) {
      attachedExamIdToName.set(standaloneAttachedId, "Exam");
    }

    if (attachedExamIdToName.size === 0) return null;

    const performances = ((candidate?.candidate as any)?.examPerformances ||
      []) as any[];

    const matched = performances
      .filter((performance) => {
        const examId = Number(performance?.examId ?? performance?.exam_id);
        const status = String(performance?.status || "").toUpperCase();
        const isCompleted =
          status === "COMPLETED" ||
          !!performance?.endTime ||
          !!performance?.end_time ||
          Number.isFinite(Number(performance?.percentage)) ||
          String(performance?.score || "").trim().length > 0;

        return (
          attachedExamIdToName.has(examId) &&
          isCompleted &&
          String(performance?.score || "").trim().length > 0
        );
      })
      .sort((a, b) => {
        const aTime = new Date(
          a?.endTime || a?.end_time || a?.updatedAt || a?.createdAt || 0,
        ).getTime();
        const bTime = new Date(
          b?.endTime || b?.end_time || b?.updatedAt || b?.createdAt || 0,
        ).getTime();
        return bTime - aTime;
      });

    const latest = matched[0];
    if (!latest) return null;

    const examId = Number(latest?.examId ?? latest?.exam_id);
    const examName = attachedExamIdToName.get(examId) || "Exam";
    let percentage: string | null = null;
    const rawPercentage = Number(latest?.percentage);
    if (Number.isFinite(rawPercentage)) {
      percentage = rawPercentage.toFixed(2);
    } else {
      const rawScore = String(latest?.score || "");
      const scorePairMatch = rawScore.match(/(\d+)\s*\/\s*(\d+)/);
      if (scorePairMatch) {
        const obtained = Number(scorePairMatch[1]);
        const total = Number(scorePairMatch[2]);
        if (Number.isFinite(obtained) && Number.isFinite(total) && total > 0) {
          percentage = ((obtained / total) * 100).toFixed(2);
        }
      } else {
        const numericScore = Number(rawScore);
        if (Number.isFinite(numericScore)) {
          percentage = numericScore.toFixed(2);
        }
      }
    }
    if (!percentage) return null;

    return {
      performanceId: Number(latest?.id),
      examId,
      examName,
      percentage,
    };
  };

  useEffect(() => {
    setPageInfo("/?page=1");
    setApplicants([]); // reset the applicants array
  }, [jobId, sortOption]);

  useEffect(() => {
    pageInfo == "/?page=1" && FetchApplicants();
  }, [pageInfo]);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (dataLoadedRef.current) return;
    dataLoadedRef.current = true;
    loadInterviewsLookup();
    loadAttachedSkillExamLookup();
  }, []);

  return (
    <div className="widget-content all-applicants-enhanced">
      {getIsLoading && <UseFullScreenLoader text={"Please Hang On..."} />}
      <div className="tabs-box">
        <Tabs>
          <div className="aplicants-upper-bar d-flex justify-content-center">
            {/* <h6 className="pb-3">{jobTitle}</h6> */}

            <TabList className="aplicantion-status tab-buttons clearfix d-flex justify-content-between w-100">
              <Tab className="tab-btn ms-0 totals">
                Total: {getTotalApplicants.toString()}
              </Tab>
              <Tab className="tab-btn ms-0 approved">
                Selected: {getApproveCount.toString()}
              </Tab>
              <Tab className="tab-btn ms-0 pending">
                Pending: {getPendingCount.toString()}
              </Tab>
              <Tab className="tab-btn ms-0 rejected">
                {" "}
                Rejected: {getRejectCount.toString()}
              </Tab>
              <Tab className="tab-btn ms-0 shortlisted">
                {" "}
                Shortlisted: {getShortlistCount.toString()}
              </Tab>
            </TabList>
          </div>

          <div className="tabs-content">
            <TabPanel>
              <InfiniteScroll
                dataLength={getApplicants!.length}
                next={FetchApplicants}
                hasMore={pageInfo !== null}
                style={{ overflow: "visible" }}
                // scrollableTarget="scrollable_div"
                endMessage={
                  <p style={{ textAlign: "center" }}>
                    Yay 🎉 You have reached the end.
                  </p>
                }
                loader={
                  <div className="d-flex justify-content-center py-3">
                    <Oval
                      visible={true}
                      height="40"
                      width="40"
                      color="#055875"
                      secondaryColor="#055875c2"
                      ariaLabel="oval-loading"
                    />
                  </div>
                }
              >
                <div className="row">
                  {getApplicants.map((candidate: JobApplication, index) => (
                    <div
                      className="candidate-block-three col-lg-6 col-md-12 col-sm-12"
                      key={`${candidate.candidateId}-${candidate.jobPostId}`}
                    >
                      <div className="inner-box h-100">
                        <ul className="option-list card-tools-top position-absolute top-0 end-0 me-2 mt-1">
                          <li className="m-0 ">
                            <button
                              data-text={
                                isInterviewFeedbackEnabled(candidate)
                                  ? "Interview Feedback"
                                  : "Feedback available after interview is finished"
                              }
                              title={
                                isInterviewFeedbackEnabled(candidate)
                                  ? "Interview Feedback"
                                  : "Feedback available after interview is finished"
                              }
                              disabled={!isInterviewFeedbackEnabled(candidate)}
                              data-bs-toggle="modal"
                              data-bs-target="#sharedFeedbackModal"
                              onClick={() => {
                                if (isInterviewFeedbackEnabled(candidate)) {
                                  openFeedbackModal(candidate);
                                }
                              }}
                            >
                              <svg
                                fill="#000000"
                                height="30px"
                                width="30px"
                                version="1.1"
                                id="Layer_1"
                                xmlns="http://www.w3.org/2000/svg"
                                xmlnsXlink="http://www.w3.org/1999/xlink"
                                viewBox="0 0 480 480"
                                xmlSpace="preserve"
                              >
                                <g>
                                  <g>
                                    <g>
                                      <path
                                        d="M391.502,210.725c-5.311-1.52-10.846,1.555-12.364,6.865c-1.519,5.31,1.555,10.846,6.864,12.364
                                                                                    C431.646,243.008,460,261.942,460,279.367c0,12.752-15.51,26.749-42.552,38.402c-29.752,12.82-71.958,22.2-118.891,26.425
                                                                                    l-40.963-0.555c-0.047,0-0.093-0.001-0.139-0.001c-5.46,0-9.922,4.389-9.996,9.865c-0.075,5.522,4.342,10.06,9.863,10.134
                                                                                    l41.479,0.562c0.046,0,0.091,0.001,0.136,0.001c0.297,0,0.593-0.013,0.888-0.039c49.196-4.386,93.779-14.339,125.538-28.024
                                                                                    C470.521,316.676,480,294.524,480,279.367C480,251.424,448.57,227.046,391.502,210.725z"
                                      />
                                      <path
                                        d="M96.879,199.333c-5.522,0-10,4.477-10,10c0,5.523,4.478,10,10,10H138v41.333H96.879c-5.522,0-10,4.477-10,10
                                                                                    s4.478,10,10,10H148c5.523,0,10-4.477,10-10V148c0-5.523-4.477-10-10-10H96.879c-5.522,0-10,4.477-10,10s4.478,10,10,10H138
                                                                                    v41.333H96.879z"
                                      />
                                      <path
                                        d="M188.879,280.667h61.334c5.522,0,10-4.477,10-10v-61.333c0-5.523-4.477-10-10-10h-51.334V158H240c5.523,0,10-4.477,10-10
                                                                                    s-4.477-10-10-10h-51.121c-5.523,0-10,4.477-10,10v122.667C178.879,276.19,183.356,280.667,188.879,280.667z M198.879,219.333
                                                                                    h41.334v41.333h-41.334V219.333z"
                                      />
                                      <path
                                        d="M291.121,280.667h61.334c5.522,0,10-4.477,10-10V148c0-5.523-4.478-10-10-10h-61.334c-5.522,0-10,4.477-10,10v122.667
                                                                                    C281.121,276.19,285.599,280.667,291.121,280.667z M301.121,158h41.334v102.667h-41.334V158z"
                                      />
                                      <path
                                        d="M182.857,305.537c-3.567-4.216-9.877-4.743-14.093-1.176c-4.217,3.567-4.743,9.876-1.177,14.093l22.366,26.44
                                                                                    c-47.196-3.599-89.941-12.249-121.37-24.65C37.708,308.06,20,293.162,20,279.367c0-16.018,23.736-33.28,63.493-46.176
                                                                                    c5.254-1.704,8.131-7.344,6.427-12.598c-1.703-5.253-7.345-8.13-12.597-6.427c-23.129,7.502-41.47,16.427-54.515,26.526
                                                                                    C7.674,252.412,0,265.423,0,279.367c0,23.104,21.178,43.671,61.242,59.48c32.564,12.849,76.227,21.869,124.226,25.758
                                                                                    l-19.944,22.104c-3.7,4.1-3.376,10.424,0.725,14.123c1.912,1.726,4.308,2.576,6.696,2.576c2.731,0,5.453-1.113,7.427-3.301
                                                                                    l36.387-40.325c1.658-1.837,2.576-4.224,2.576-6.699v-0.764c0-2.365-0.838-4.653-2.365-6.458L182.857,305.537z"
                                      />
                                      <path
                                        d="M381.414,137.486h40.879c5.522,0,10-4.477,10-10V86.592c0-5.523-4.478-10-10-10h-40.879c-5.522,0-10,4.477-10,10v40.894
                                                                                    C371.414,133.009,375.892,137.486,381.414,137.486z M391.414,96.592h20.879v20.894h-20.879V96.592z"
                                      />
                                    </g>
                                  </g>
                                </g>
                              </svg>
                            </button>
                          </li>
                          {candidate.status == "Approved" && (
                            <li>
                              <button
                                data-text="View Guarantor Details"
                                data-bs-toggle="modal"
                                data-bs-target={`#guarantorCommunicationModal${index}`}
                              >
                                <span className="la la-users-cog"></span>
                              </button>
                            </li>
                          )}
                        </ul>

                        <div className="content">
                          <figure className="image">
                            <img
                              onError={(e) => {
                                e.currentTarget.src =
                                  "/images/human_capital_logo.png";
                                e.currentTarget.onerror = null;
                              }}
                              src={
                                candidate?.candidate?.profilePictureUrl ||
                                "/images/human_capital_logo.png"
                              }
                              alt="candidates profile"
                            />
                          </figure>
                          <div className="d-flex justify-content-between align-items-start">
                            <h4 className="name d-flex justify-content-between align-items-start gap-3">
                              <Link
                                href={`/candidate/${candidate.candidate.id}`}
                              >
                                {candidate?.candidate?.firstName ||
                                candidate?.candidate?.lastName
                                  ? `${
                                      candidate?.candidate?.firstName || ""
                                    } ${candidate?.candidate?.lastName || ""}`.trim()
                                  : "Not Available"}
                              </Link>
                            </h4>
                          </div>

                          <ul className="candidate-info">
                            <li>
                              <span className="icon flaticon-map-locator"></span>{" "}
                              {(() => {
                                const city = candidate?.candidate?.city || "";
                                const state = candidate?.candidate?.state || "";
                                const country =
                                  candidate?.candidate?.country || "";
                                if (city && state && country) {
                                  return `${city}, ${state}, ${country}`;
                                } else if (city && state) {
                                  return `${city}, ${state}`;
                                } else if (city && country) {
                                  return `${city}, ${country}`;
                                } else if (state && country) {
                                  return `${state}, ${country}`;
                                } else if (city) {
                                  return city;
                                } else if (state) {
                                  return state;
                                } else if (country) {
                                  return country;
                                } else {
                                  return "Not available";
                                }
                              })()}
                            </li>
                          </ul>
                          {/* End candidate-info */}

                          {(() => {
                            const attachedScoreInfo =
                              getAttachedExamScoreInfo(candidate);
                            if (!attachedScoreInfo) return null;

                            return (
                              <div className="mb-2">
                                <span
                                  className="badge"
                                  style={{
                                    backgroundColor: "#055875",
                                    color: "white",
                                    display: "inline-block",
                                    padding: "6px 10px",
                                    borderRadius: "7px",
                                    fontSize: "13px",
                                    whiteSpace: "normal",
                                    lineHeight: "1.2",
                                  }}
                                >
                                  {`${attachedScoreInfo.examName} : ${attachedScoreInfo.percentage}%`}
                                </span>
                              </div>
                            );
                          })()}

                          <ul className="post-tags">
                            {candidate?.candidate?.skills &&
                              candidate?.candidate?.skills
                                .slice(0, 4)
                                .map((val, i) => (
                                  <li key={i}>
                                    <a href="#">{val?.name}</a>
                                  </li>
                                ))}
                          </ul>
                        </div>
                        {/* End content */}

                        <div className="option-box status-positioning">
                          <ul className="option-list applicant-status">
                            <li>
                              <Link
                                href={`/jobs/${candidate?.jobPostId}`}
                                data-text="View Job"
                              >
                                {" "}
                                <span className="la la-eye"></span>
                              </Link>
                            </li>
                            {candidate.status !== "Approved" && (
                              <li>
                                <button
                                  onClick={() => {
                                    setIsRejectModalOpen(false);
                                    setIsShortlistModalOpen(false);
                                    setIsApproveModalOpen(true);

                                    handleStatusChange(
                                      candidate?.jobPostId,
                                      candidate?.candidateId,
                                      "Approved",
                                    );
                                  }}
                                  data-text="Mark as Selected"
                                  className=" bg-success bg-opacity-50"
                                >
                                  <span className="la la-check"></span>
                                </button>
                              </li>
                            )}
                            {candidate.status !== "Rejected" && (
                              <li>
                                <button
                                  onClick={() => {
                                    setIsApproveModalOpen(false);
                                    setIsShortlistModalOpen(false);
                                    setIsRejectModalOpen(true);

                                    handleStatusChange(
                                      candidate?.jobPostId,
                                      candidate?.candidateId,
                                      "Rejected",
                                    );

                                    console.log(
                                      "isRejectModalOpen>>>",
                                      isRejectModalOpen,
                                    );
                                    console.log(
                                      "isApproveModalOpen>>>",
                                      isApproveModalOpen,
                                    );
                                    console.log(
                                      "isShortlistModalOpen>>>",
                                      isShortlistModalOpen,
                                    );
                                  }}
                                  className=" bg-danger bg-opacity-50"
                                  data-text="Reject Application"
                                >
                                  <span className="la la-times-circle"></span>
                                </button>
                              </li>
                            )}
                            {candidate.status !== "Shortlisted" && (
                              <li>
                                <button
                                  onClick={() => {
                                    setIsApproveModalOpen(false);
                                    setIsRejectModalOpen(false);
                                    setIsShortlistModalOpen(true);

                                    handleStatusChange(
                                      candidate?.jobPostId,
                                      candidate?.candidateId,
                                      "Shortlisted",
                                    );

                                    console.log(
                                      "isShortlistModalOpen>>>",
                                      isShortlistModalOpen,
                                    );
                                  }}
                                  data-text="Shortlist Application"
                                >
                                  <span className="la la-bookmark"></span>
                                </button>
                              </li>
                            )}

                            <li>
                              <Link
                                href={`${candidate?.documents?.[0]?.files[0]?.url ? candidate?.documents![0]?.files[0]?.url : "#"}`}
                                data-text="View CV"
                              >
                                <span
                                  style={{
                                    fontSize: "13px",
                                  }}
                                >
                                  CV
                                </span>
                              </Link>
                            </li>
                            {(() => {
                              const attachedScoreInfo =
                                getAttachedExamScoreInfo(candidate);

                              if (!attachedScoreInfo?.performanceId) {
                                return null;
                              }

                              return (
                                <li>
                                  <button
                                    type="button"
                                    data-text="View Results"
                                    onClick={() =>
                                      router.push(
                                        `/dashboard/skill-test/result?performanceId=${attachedScoreInfo.performanceId}`,
                                      )
                                    }
                                  >
                                    <span className="la la-chart-bar"></span>
                                  </button>
                                </li>
                              );
                            })()}
                          </ul>
                          <div className="applicant-status-chip-wrap">
                            <p className="mb-0 status-background">
                              <span
                                className={`${candidate?.status === "Approved" ? "text-success" : candidate?.status === "Rejected" ? "text-danger" : candidate?.status === "Pending" ? "text-warning" : "text-primary"}`}
                              >
                                {candidate?.status === "Approved"
                                  ? "Selected "
                                  : candidate?.status}
                              </span>
                            </p>
                          </div>
                          <div
                            className="modal fade"
                            id={`statusModal${index}`}
                            tabIndex={-1}
                            aria-labelledby="exampleModalLabel"
                            aria-hidden="true"
                          >
                            <div className="modal-dialog modal-xl">
                              <div className="modal-content">
                                <div className="modal-header">
                                  <button
                                    type="button"
                                    className="btn-close"
                                    data-bs-dismiss="modal"
                                    aria-label="Close"
                                  ></button>
                                </div>
                                <div className="modal-body">
                                  {(() => {
                                    const fb =
                                      getResolvedInterviewDetailsStable(
                                        candidate,
                                      ).fallbackFeedback;
                                    const readonlyFeedback: InterviewFeedbackPayload =
                                      {
                                        workStandard: fb?.workStandard ?? null,
                                        errorFreeness:
                                          fb?.errorFreeness ?? null,
                                        helpToImprove:
                                          fb?.helpToImprove ?? null,
                                        communicationSkill:
                                          fb?.communicationSkill ?? null,
                                        listeningSkill:
                                          fb?.listeningSkill ?? null,
                                        informationSharing:
                                          fb?.informationSharing ?? null,
                                        remarks: fb?.remarks ?? "",
                                      };
                                    return (
                                      <InterviewFeedbackForm
                                        feedback={readonlyFeedback}
                                        mode="candidate"
                                        title="Interview Feedback"
                                        subtitle="For Evaluating Candidates"
                                        radioGroupPrefix={`status-${index}`}
                                        disabled={true}
                                      />
                                    );
                                  })()}
                                </div>
                                <div className="modal-footer">
                                  <button
                                    type="button"
                                    className="btn btn-secondary"
                                    data-bs-dismiss="modal"
                                  >
                                    Close
                                  </button>
                                </div>
                              </div>
                            </div>
                          </div>

                          {/* Guaranteer Modal */}
                          {candidate.status == "Approved" && (
                            <GuarantorCommunicationModal
                              applicationId={candidate.id}
                              index={index}
                              guarantors={candidate.applicationGuarantors}
                              isFromCompany={true}
                              candidateId={candidate.candidateId}
                            />
                          )}
                        </div>
                        {/* End admin options box */}
                      </div>
                    </div>
                  ))}
                </div>
              </InfiniteScroll>
            </TabPanel>
            {/* End total applicants */}
            <TabPanel>
              <InfiniteScroll
                dataLength={getApplicants!.length}
                next={FetchApplicants}
                hasMore={pageInfo !== null}
                style={{ overflow: "visible" }}
                // scrollableTarget="scrollable_div"
                endMessage={
                  <p style={{ textAlign: "center" }}>
                    Yay 🎉 You have reached the end.
                  </p>
                }
                loader={
                  <div className="d-flex justify-content-center py-3">
                    <Oval
                      visible={true}
                      height="40"
                      width="40"
                      color="#055875"
                      secondaryColor="#055875c2"
                      ariaLabel="oval-loading"
                    />
                  </div>
                }
              >
                <div className="row">
                  {getApplicants.map((candidate, index) => (
                    <>
                      {candidate.status === "Approved" && (
                        <div
                          className="candidate-block-three col-lg-6 col-md-12 col-sm-12"
                          key={index}
                        >
                          <div className="inner-box">
                            <div className="content">
                              <figure className="image">
                                <img
                                  onError={(e) => {
                                    e.currentTarget.src =
                                      "/images/human_capital_logo.png";
                                    e.currentTarget.onerror = null;
                                  }}
                                  src={
                                    candidate?.candidate?.profilePictureUrl ||
                                    "/images/human_capital_logo.png"
                                  }
                                  alt="candidates profile"
                                />
                              </figure>
                              <h4 className="name">
                                <Link
                                  href={`/candidate/${candidate.candidate.id}`}
                                >
                                  {candidate?.candidate?.firstName ||
                                  candidate?.candidate?.lastName
                                    ? `${
                                        candidate?.candidate?.firstName || ""
                                      } ${candidate?.candidate?.lastName || ""}`.trim()
                                    : "Not Available"}
                                </Link>
                              </h4>
                              <ul className="candidate-info">
                                <li>
                                  <span className="icon flaticon-map-locator"></span>{" "}
                                  {(() => {
                                    const city =
                                      candidate?.candidate?.city || "";
                                    const state =
                                      candidate?.candidate?.state || "";
                                    const country =
                                      candidate?.candidate?.country || "";
                                    if (city && state && country) {
                                      return `${city}, ${state}, ${country}`;
                                    } else if (city && state) {
                                      return `${city}, ${state}`;
                                    } else if (city && country) {
                                      return `${city}, ${country}`;
                                    } else if (state && country) {
                                      return `${state}, ${country}`;
                                    } else if (city) {
                                      return city;
                                    } else if (state) {
                                      return state;
                                    } else if (country) {
                                      return country;
                                    } else {
                                      return "Not available";
                                    }
                                  })()}
                                </li>
                              </ul>
                              {/* End candidate-info */}

                              <ul className="post-tags">
                                {candidate.candidate.skills &&
                                  candidate.candidate.skills
                                    .slice(0, 4)
                                    .map((val, i) => (
                                      <li key={i}>
                                        <a href="#">{val.name}</a>
                                      </li>
                                    ))}
                              </ul>
                            </div>
                            {/* End content */}

                            <div className="option-box status-positioning ">
                              <ul className="option-list">
                                <li>
                                  <Link
                                    href={`/dashboard/manage-jobs/${candidate?.jobPostId}`}
                                    data-text="View Job"
                                  >
                                    {" "}
                                    <span className="la la-eye"></span>
                                  </Link>
                                </li>

                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Rejected",
                                      )
                                    }
                                    className=" bg-danger bg-opacity-50"
                                    data-text="Reject Application"
                                  >
                                    <span className="la la-times-circle"></span>
                                  </button>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Shortlisted",
                                      )
                                    }
                                    data-text="Shortlist Application"
                                  >
                                    <span className="la la-bookmark"></span>
                                  </button>
                                </li>
                              </ul>
                              <div>
                                <Link
                                  href={`${candidate?.documents?.[0]?.files[0]?.url ? candidate?.documents![0]?.files[0]?.url : "#"}`}
                                  target="_blank"
                                >
                                  <img
                                    data-text="View CV"
                                    alt="Resume"
                                    src="/images/cv.png"
                                    width={25}
                                    height={25}
                                  ></img>
                                </Link>
                              </div>
                            </div>
                            {/* End admin options box */}
                          </div>
                        </div>
                      )}
                    </>
                  ))}
                </div>
              </InfiniteScroll>
            </TabPanel>
            {/* End approved */}
            <TabPanel>
              <InfiniteScroll
                dataLength={getApplicants!.length}
                next={FetchApplicants}
                hasMore={pageInfo !== null}
                style={{ overflow: "visible" }}
                // scrollableTarget="scrollable_div"
                endMessage={
                  <p style={{ textAlign: "center" }}>
                    Yay 🎉 You have reached the end.
                  </p>
                }
                loader={
                  <div className="d-flex justify-content-center py-3">
                    <Oval
                      visible={true}
                      height="40"
                      width="40"
                      color="#055875"
                      secondaryColor="#055875c2"
                      ariaLabel="oval-loading"
                    />
                  </div>
                }
              >
                <div className="row">
                  {getApplicants.map((candidate, index) => (
                    <>
                      {candidate.status === "Pending" && (
                        <div
                          className="candidate-block-three col-lg-6 col-md-12 col-sm-12"
                          key={index}
                        >
                          <div className="inner-box">
                            <div className="content">
                              <figure className="image">
                                <img
                                  onError={(e) => {
                                    e.currentTarget.src =
                                      "/images/human_capital_logo.png";
                                    e.currentTarget.onerror = null;
                                  }}
                                  src={
                                    candidate?.candidate?.profilePictureUrl ||
                                    "/images/human_capital_logo.png"
                                  }
                                  alt="candidates profile"
                                />
                              </figure>
                              <h4 className="name">
                                <Link
                                  href={`/candidate/${candidate.candidate.id}`}
                                >
                                  {candidate?.candidate?.firstName ||
                                  candidate?.candidate?.lastName
                                    ? `${
                                        candidate?.candidate?.firstName || ""
                                      } ${candidate?.candidate?.lastName || ""}`.trim()
                                    : "Not Available"}
                                </Link>
                              </h4>
                              <ul className="candidate-info">
                                <li>
                                  <span className="icon flaticon-map-locator"></span>{" "}
                                  {(() => {
                                    const city =
                                      candidate?.candidate?.city || "";
                                    const state =
                                      candidate?.candidate?.state || "";
                                    const country =
                                      candidate?.candidate?.country || "";
                                    if (city && state && country) {
                                      return `${city}, ${state}, ${country}`;
                                    } else if (city && state) {
                                      return `${city}, ${state}`;
                                    } else if (city && country) {
                                      return `${city}, ${country}`;
                                    } else if (state && country) {
                                      return `${state}, ${country}`;
                                    } else if (city) {
                                      return city;
                                    } else if (state) {
                                      return state;
                                    } else if (country) {
                                      return country;
                                    } else {
                                      return "Not available";
                                    }
                                  })()}
                                </li>
                              </ul>
                              {/* End candidate-info */}

                              <ul className="post-tags">
                                {candidate.candidate.skills &&
                                  candidate.candidate.skills
                                    .slice(0, 4)
                                    .map((val, i) => (
                                      <li key={i}>
                                        <a href="#">{val.name}</a>
                                      </li>
                                    ))}
                              </ul>
                            </div>
                            {/* End content */}

                            <div className="option-box status-positioning">
                              <ul className="option-list">
                                <li>
                                  <Link
                                    href={`/dashboard/manage-jobs/${candidate?.jobPostId}`}
                                    data-text="View Job"
                                  >
                                    {" "}
                                    <span className="la la-eye"></span>
                                  </Link>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Approved",
                                      )
                                    }
                                    className=" bg-success bg-opacity-50"
                                    data-text="Mark as Selected"
                                  >
                                    <span className="la la-check"></span>
                                  </button>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Rejected",
                                      )
                                    }
                                    className=" bg-danger bg-opacity-50"
                                    data-text="Reject Application"
                                  >
                                    <span className="la la-times-circle"></span>
                                  </button>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Shortlisted",
                                      )
                                    }
                                    data-text="Shortlist Application"
                                  >
                                    <span className="la la-bookmark"></span>
                                  </button>
                                </li>
                              </ul>
                              <div>
                                <Link
                                  href={`${candidate?.documents?.[0]?.files[0]?.url ? candidate?.documents![0]?.files[0]?.url : "#"}`}
                                  target="_blank"
                                >
                                  <img
                                    data-text="View CV"
                                    alt="Resume"
                                    src="/images/cv.png"
                                    width={25}
                                    height={25}
                                  ></img>
                                </Link>
                              </div>
                            </div>
                            {/* End admin options box */}
                          </div>
                        </div>
                      )}
                    </>
                  ))}
                </div>
              </InfiniteScroll>
            </TabPanel>
            {/* End pending */}

            <TabPanel>
              <InfiniteScroll
                dataLength={getApplicants!.length}
                next={FetchApplicants}
                hasMore={pageInfo !== null}
                style={{ overflow: "visible" }}
                // scrollableTarget="scrollable_div"
                endMessage={
                  <p style={{ textAlign: "center" }}>
                    Yay 🎉 You have reached the end.
                  </p>
                }
                loader={
                  <div className="d-flex justify-content-center py-3">
                    <Oval
                      visible={true}
                      height="40"
                      width="40"
                      color="#055875"
                      secondaryColor="#055875c2"
                      ariaLabel="oval-loading"
                    />
                  </div>
                }
              >
                <div className="row">
                  {getApplicants.map((candidate, index) => (
                    <>
                      {candidate.status === "Rejected" && (
                        <div
                          className="candidate-block-three col-lg-6 col-md-12 col-sm-12"
                          key={index}
                        >
                          <div className="inner-box">
                            <div className="content">
                              <figure className="image">
                                <img
                                  onError={(e) => {
                                    e.currentTarget.src =
                                      "/images/human_capital_logo.png";
                                    e.currentTarget.onerror = null;
                                  }}
                                  src={
                                    candidate?.candidate?.profilePictureUrl ||
                                    "/images/human_capital_logo.png"
                                  }
                                  alt="candidates profile"
                                />
                              </figure>
                              <h4 className="name">
                                <Link
                                  href={`/candidate/${candidate.candidate.id}`}
                                >
                                  {candidate?.candidate?.firstName ||
                                  candidate?.candidate?.lastName
                                    ? `${
                                        candidate?.candidate?.firstName || ""
                                      } ${candidate?.candidate?.lastName || ""}`.trim()
                                    : "Not Available"}
                                </Link>
                              </h4>
                              <ul className="candidate-info">
                                <li>
                                  <span className="icon flaticon-map-locator"></span>{" "}
                                  {(() => {
                                    const city =
                                      candidate?.candidate?.city || "";
                                    const state =
                                      candidate?.candidate?.state || "";
                                    const country =
                                      candidate?.candidate?.country || "";
                                    if (city && state && country) {
                                      return `${city}, ${state}, ${country}`;
                                    } else if (city && state) {
                                      return `${city}, ${state}`;
                                    } else if (city && country) {
                                      return `${city}, ${country}`;
                                    } else if (state && country) {
                                      return `${state}, ${country}`;
                                    } else if (city) {
                                      return city;
                                    } else if (state) {
                                      return state;
                                    } else if (country) {
                                      return country;
                                    } else {
                                      return "Not available";
                                    }
                                  })()}
                                </li>
                              </ul>
                              {/* End candidate-info */}

                              <ul className="post-tags">
                                {candidate.candidate.skills &&
                                  candidate.candidate.skills
                                    .slice(0, 4)
                                    .map((val, i) => (
                                      <li key={i}>
                                        <a href="#">{val.name}</a>
                                      </li>
                                    ))}
                              </ul>
                            </div>
                            {/* End content */}

                            <div className="option-box status-positioning">
                              <ul className="option-list">
                                <li>
                                  <Link
                                    href={`/dashboard/manage-jobs/${candidate?.jobPostId}`}
                                    data-text="View Job"
                                  >
                                    {" "}
                                    <span className="la la-eye"></span>
                                  </Link>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Approved",
                                      )
                                    }
                                    className=" bg-success bg-opacity-50"
                                    data-text="Mark as Selected"
                                  >
                                    <span className="la la-check"></span>
                                  </button>
                                </li>

                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Rejected",
                                      )
                                    }
                                    data-text="Shortlist Application"
                                  >
                                    <span className="la la-bookmark"></span>
                                  </button>
                                </li>
                              </ul>
                              <div>
                                <Link
                                  href={`${candidate?.documents?.[0]?.files[0]?.url ? candidate?.documents![0]?.files[0]?.url : "#"}`}
                                  target="_blank"
                                >
                                  <img
                                    data-text="View CV"
                                    alt="Resume"
                                    src="/images/cv.png"
                                    width={25}
                                    height={25}
                                  ></img>
                                </Link>
                              </div>
                            </div>
                            {/* End admin options box */}
                          </div>
                        </div>
                      )}
                    </>
                  ))}
                </div>
              </InfiniteScroll>
            </TabPanel>
            {/* End rejected */}

            <TabPanel>
              <InfiniteScroll
                dataLength={getApplicants!.length}
                next={FetchApplicants}
                hasMore={pageInfo !== null}
                style={{ overflow: "visible" }}
                // scrollableTarget="scrollable_div"
                endMessage={
                  <p style={{ textAlign: "center" }}>
                    Yay 🎉 You have reached the end.
                  </p>
                }
                loader={
                  <div className="d-flex justify-content-center py-3">
                    <Oval
                      visible={true}
                      height="40"
                      width="40"
                      color="#055875"
                      secondaryColor="#055875c2"
                      ariaLabel="oval-loading"
                    />
                  </div>
                }
              >
                <div className="row">
                  {getApplicants.map((candidate, index) => (
                    <>
                      {candidate.status === "Shortlisted" && (
                        <div
                          className="candidate-block-three col-lg-6 col-md-12 col-sm-12"
                          key={index}
                        >
                          <div className="inner-box">
                            <div className="content">
                              <figure className="image">
                                <img
                                  onError={(e) => {
                                    e.currentTarget.src =
                                      "/images/human_capital_logo.png";
                                    e.currentTarget.onerror = null;
                                  }}
                                  src={
                                    candidate?.candidate?.profilePictureUrl ||
                                    "/images/human_capital_logo.png"
                                  }
                                  alt="candidates profile"
                                />
                              </figure>
                              <h4 className="name">
                                <Link
                                  href={`/candidate/${candidate.candidate.id}`}
                                >
                                  {candidate?.candidate?.firstName ||
                                  candidate?.candidate?.lastName
                                    ? `${
                                        candidate?.candidate?.firstName || ""
                                      } ${candidate?.candidate?.lastName || ""}`.trim()
                                    : "Not Available"}
                                </Link>
                              </h4>
                              <ul className="candidate-info">
                                <li>
                                  <span className="icon flaticon-map-locator"></span>{" "}
                                  {(() => {
                                    const city =
                                      candidate?.candidate?.city || "";
                                    const state =
                                      candidate?.candidate?.state || "";
                                    const country =
                                      candidate?.candidate?.country || "";
                                    if (city && state && country) {
                                      return `${city}, ${state}, ${country}`;
                                    } else if (city && state) {
                                      return `${city}, ${state}`;
                                    } else if (city && country) {
                                      return `${city}, ${country}`;
                                    } else if (state && country) {
                                      return `${state}, ${country}`;
                                    } else if (city) {
                                      return city;
                                    } else if (state) {
                                      return state;
                                    } else if (country) {
                                      return country;
                                    } else {
                                      return "Not available";
                                    }
                                  })()}
                                </li>
                              </ul>
                              {/* End candidate-info */}

                              <ul className="post-tags">
                                {candidate.candidate.skills &&
                                  candidate.candidate.skills
                                    .slice(0, 4)
                                    .map((val, i) => (
                                      <li key={i}>
                                        <a href="#">{val.name}</a>
                                      </li>
                                    ))}
                              </ul>
                            </div>
                            {/* End content */}

                            <div className="option-box status-positioning">
                              <ul className="option-list">
                                <li>
                                  <Link
                                    href={`/dashboard/manage-jobs/${candidate?.jobPostId}`}
                                    data-text="View Job"
                                  >
                                    {" "}
                                    <span className="la la-eye"></span>
                                  </Link>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Approved",
                                      )
                                    }
                                    className=" bg-success bg-opacity-50"
                                    data-text="Mark as Selected"
                                  >
                                    <span className="la la-check"></span>
                                  </button>
                                </li>
                                <li>
                                  <button
                                    onClick={() =>
                                      handleStatusChange(
                                        candidate?.jobPostId,
                                        candidate?.candidateId,
                                        "Rejected",
                                      )
                                    }
                                    className=" bg-danger bg-opacity-50"
                                    data-text="Reject Application"
                                  >
                                    <span className="la la-times-circle"></span>
                                  </button>
                                </li>
                              </ul>
                              <div>
                                <Link
                                  href={`${candidate?.documents?.[0]?.files[0]?.url ? candidate?.documents![0]?.files[0]?.url : "#"}`}
                                  target="_blank"
                                >
                                  <img
                                    data-text="View CV"
                                    alt="Resume"
                                    src="/images/cv.png"
                                    width={25}
                                    height={25}
                                  ></img>
                                </Link>
                              </div>
                            </div>
                            {/* End admin options box */}
                          </div>
                        </div>
                      )}
                    </>
                  ))}
                </div>
              </InfiniteScroll>
            </TabPanel>
            {/* End shortlisted applicants */}
          </div>
        </Tabs>
      </div>

      <InterviewFeedbackModal
        candidateData={activeFeedbackCandidate}
        onClose={() => setActiveFeedbackCandidate(null)}
      />
    </div>
  );
};

export default WidgetContentBox;
