import Link from "next/link";
import { useRouter } from "next/router";
import { ChangeEvent, FC, 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 { useGetFileName } from "../../hooks/useGetFileName";
import { useGetUploadedResumes, useUploadResume } from "../../utils/hooks";
import { useApplyJob } from "../../utils/hooks/useApplyJob";

interface applyJobRep {
  resp: {
    success: boolean;
  };
  status: number;
}
interface PageProps {
  jobId: number;
  closeApplyJobModal: any;
}
function checkFileTypes(file: File | null): boolean {
  const allowedTypes = [
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  ];
  if (!file) {
    return false;
  }
  return allowedTypes.includes(file.type);
}
interface CvMeta {
  cvTitle: string;
  cvId: number | null;
}

const ApplyJobModalContent: FC<PageProps> = ({ jobId, closeApplyJobModal }) => {
  const [getLoading, setLoading] = useState(false);
  const [uploadedResumes, setUploadedResumes] = useState<UploadedDocResp[]>([]);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [getError, setError] = useState<string>("");
  const [title, setTitle] = useState<string>("");
  const [getLastUploadedDoc, setLastUploadedDoc] = useState<{
    title: string;
    id: number;
  }>();
  const [cvMeta, setCvMeta] = useState<CvMeta>({
    cvTitle: "Select a CV",
    cvId: null,
  });

  const [pageInfo, setPageInfo] = useState<string | null>("/?page=1");
  const router = useRouter();

  // function to get the uploaded documents when page refreshes
  useEffect(() => {
    getUploadedDocuments();
  }, []);

  // apply job function
  const applyJob = async (data: any) => {
    setLoading(true);
    try {
      const applyJobRep = (await useApplyJob(
        jobId,
        Number(data.cvId)
      )) as applyJobRep;
      if (applyJobRep.status === 200) {
        await Swal.fire({
          title: "Success!",
          text: "Job Applied Successfully!",
          icon: "success",
          confirmButtonColor: "#055875",
          iconColor: "#055875",
        });
        closeApplyJobModal.current?.click();
        router.push("/dashboard/applied-jobs");
      } else if (applyJobRep.status === 500) {
        await Swal.fire({
          title: "Failed!",
          text: "Internal Server Error!",
          icon: "warning",
          confirmButtonColor: "#055875",
          iconColor: "#055875",
        });
      }
    } catch (error) {
      await Swal.fire({
        title: "Failed!",
        text: "You can apply to a job Only Once!",
        icon: "warning",
        confirmButtonColor: "#055875",
        iconColor: "#055875",
      });
    } finally {
      setLoading(false);
    }
  };

  const cvManagerHandler = async (e: ChangeEvent<HTMLInputElement>) => {
    const data = e.target.files;
    setSelectedFile(data ? data[0] : null);
  };

  // function to check the fileType AND set the title here
  useEffect(() => {
    if (selectedFile !== null) {
      if (checkFileTypes(selectedFile)) {
        setError("");
        const { name } = useGetFileName(selectedFile.name);
        setTitle(name);
        title !== "" && handleUploadResume();
      } else {
        setError("Only accept (.doc, .docx, .pdf) file");
      }
    }
  }, [selectedFile, title]);

  // when the cv is uploded and after setting the last uploaded doc id, call the function to get all the uploaded documents
  useEffect(() => {
    getUploadedDocuments();
    getLastUploadedDoc &&
      setCvMeta({
        cvTitle: getLastUploadedDoc.title,
        cvId: getLastUploadedDoc.id,
      });
  }, [getLastUploadedDoc]);

  // function to upload the documents
  const handleUploadResume = async () => {
    if (getError !== "") {
      setSelectedFile(null);
      setTitle("");
    } else {
      setLoading(true);
      try {
        const { resp, status } = (await useUploadResume(
          (selectedFile ? selectedFile : null) as File,
          title
        )) as Response;

        setLoading(false);
        if (status == 200) {
          const ok = await Swal.fire({
            title: "Success!",
            text: "Document Uploaded Successfully!",
            icon: "success",
            confirmButtonColor: "#055875",
            iconColor: "#055875",
          });
          //set the last uploaded document id here
          ok && setLastUploadedDoc(resp);
        } else {
          await Swal.fire({
            title: "Failure!",
            text: "Something went wrong, Please try again!",
            icon: "warning",
            confirmButtonColor: "#055875",
            iconColor: "#055875",
          });
        }
      } catch (error) {
        setLoading(false);
        console.error("Error uploading file:", error);
        setError("Failed to upload the file");
      } finally {
        setSelectedFile(null);
        setTitle("");
      }
    }
  };
  const handleClick = (e: React.MouseEvent<HTMLLIElement>) => {
    const cvId = e.currentTarget.getAttribute("data-cvid");
    const title = e.currentTarget.getAttribute("data-title");
    console.log("clicked", cvId, title);
    setCvMeta({
      cvTitle: title!,
      cvId: Number(cvId),
    });
  };

  //function to get uploaded resumes
  const getUploadedDocuments = async () => {
    try {
      setLoading(true);
      const uploadedDocs = (await useGetUploadedResumes(
        pageInfo!
      )) as DocResponse;
      const filterResumes = uploadedDocs.data.filter(
        (doc) => doc.documentTypeId == 1 || doc.documentTypeId == 6
      );
      setUploadedResumes([...uploadedResumes, ...filterResumes]);
      setPageInfo(uploadedDocs.meta?.nextPageUrl);
    } catch (error) {
      console.error("Error fetching uploaded documents:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCVClick = () => {
    // setLoading(false);
    closeApplyJobModal.current?.click();
  };

  return (
    <>
      {getLoading && <UseFullScreenLoader text={"Loading please wait..."} />}

      <form className="default-form job-apply-form">
        <div className="row">
          <div className="col-lg-12 col-md-12 col-sm-12 form-group">
            <div className="uploading-outer apply-cv-outer">
              <div className="form-group">
                <label htmlFor="upload">Select a CV</label>
                <Link
                  className="float-end"
                  href={"/dashboard/create-own-cv"}
                  onClick={handleCreateCVClick}
                >
                  +Create Your CV
                </Link>
                <div className="dropdown">
                  <button
                    className="btn dropdown-toggle dropdown-toggle-applicant w-100 btn-outline-dark select-cv-btn"
                    type="button"
                    id="dropdownMenuButton1"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                  >
                    {cvMeta.cvTitle}
                  </button>
                  <ul
                    id="scrollable_div"
                    className="dropdown-menu dropdown-menu-applicants w-100"
                    aria-labelledby="dropdownMenuButton1"
                  >
                    <InfiniteScroll
                      dataLength={uploadedResumes!.length}
                      next={getUploadedDocuments}
                      hasMore={pageInfo != null}
                      scrollableTarget="scrollable_div"
                      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>
                      }
                    >
                      {uploadedResumes!.map((cv) => (
                        <li
                          className="px-2 py-1"
                          role="button"
                          key={cv.id}
                          data-cvid={cv.id!}
                          data-title={cv.title}
                          onClick={handleClick}
                        >
                          {cv.title}
                        </li>
                      ))}
                    </InfiniteScroll>
                  </ul>
                </div>
                {/* {errors.resumeID && errors.resumeID.type === "required" && (
                  <p className="text-danger">Please select a resume first.</p>
                )} */}
              </div>
            </div>
          </div>
          {/* End .col */}
          <div className="uploading-resume">
            <div className="uploadButton">
              <input
                className="uploadButton-input"
                type="file"
                name="attachments"
                accept=".doc,.docx,application/msword,application/pdf"
                id="upload"
                onChange={cvManagerHandler}
              />
              <label className="cv-uploadButton" htmlFor="upload">
                <span className="title">Click here to upload</span>
                <span className="text">
                  To upload file size is (Max 5Mb) and allowed file types are
                  (.doc, .docx, .pdf)
                </span>
                <span className="theme-btn btn-style-one">Upload Resume</span>
                {getError !== "" ? (
                  <p className="ui-danger mb-0">{getError}</p>
                ) : undefined}
              </label>
              <span className="uploadButton-file-name"></span>
            </div>
          </div>
          <div className="col-lg-12 col-md-12 col-sm-12 form-group">
            <button
              className={`theme-btn btn-style-one w-100 ${getLoading && "cursor-not-allowed"}`}
              type="button"
              onClick={() => applyJob(cvMeta)}
              name="submit-form"
              disabled={getLoading}
            >
              {getLoading ? "Applying Job, Please Wait..." : "Apply Job"}
            </button>
          </div>
          {/* End .col */}
        </div>
      </form>
    </>
  );
};

export default ApplyJobModalContent;
