import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import InfiniteScroll from "react-infinite-scroll-component";
import { Oval } from "react-loader-spinner";
import Swal from "sweetalert2";
import JobBlock from "../../components/common/JobBlock";
import Seo from "../../components/common/Seo";
import Comments from "../../components/company/Comments";
import PrivateMessageBox from "../../components/company/PrivateMessageBox";
import RatingModalCompany from "../../components/company/RatingModalCompany";
import Rating from "../../components/company/Ratings";
import Footer from "../../components/footer/Footer";
import DefaulHeader2 from "../../components/header/DefaulHeader2";
import MobileMenu from "../../components/header/MobileMenu";
import UseFullScreenLoader from "../../hooks/UseFullScreenLoader";
import {
  useGetCompanyDetails,
  useGetJobDetailsByCompany,
} from "../../utils/hooks";
import { useDeleteSavedJob } from "../../utils/hooks/useDeleteSavedJob";
import { useGetCompanyRating } from "../../utils/hooks/useGetCompanyRating";
import { useRateCompany } from "../../utils/hooks/useRateCompany";
import { useSavedJob } from "../../utils/hooks/useSavedJob";

const EmployersSingleV1 = () => {
  const router = useRouter();
  const [employer, setEmployersInfo] = useState<Company>();
  const id = router.query.companyName;
  const [jobList, setJobList] = useState<Job[]>([]);
  const [review, setReview] = useState<Rating>();
  const [getIsLoading, setIsLoading] = useState<boolean>(false);
  const [pageInfo, setPageInfo] = useState<string | null>("?page=1");

  const getJobList = async (savedJobCalling?: boolean) => {
    pageInfo == "?page=1" && setIsLoading(true);
    if (id) {
      try {
        if (savedJobCalling) {
          setJobList([...jobList]);
        } else {
          const { resp, status } = (await useGetJobDetailsByCompany(
            id,
            pageInfo!
          )) as FilterJobsResp;
          if (status == 200) {
            setJobList([...jobList, ...resp.data]);
            setPageInfo(resp?.meta?.nextPageUrl);
          }
        }
      } catch (error) {
        console.error("Error fetching API (Company Jobs):", error);
      } finally {
        setIsLoading(false);
      }
    }
  };
  const handleSaveJob = async (job: Job) => {
    try {
      setIsLoading(true);
      const resp = (await useSavedJob(job.id!)) as Response;
      if (resp.status === 202) {
        (await useDeleteSavedJob(job.id!)) as Response;
      }
      job.isSaved = !job.isSaved;
      // handleClearAll();
      pageInfo && getJobList(true);
    } catch (error) {
      console.error("Error fetching API (Saved Jobs):", error);
    } finally {
      setIsLoading(false);
    }
  };
  // console.log("companyName", companyName);
  const getCompanyDetails = async () => {
    setIsLoading(true);
    if (id) {
      try {
        const { resp, status } = (await useGetCompanyDetails(
          id
        )) as CompanyDetailsResp;
        setEmployersInfo(resp);
        // console.log("companyDetails>>>", employer?.profilePictureUrl);
      } catch (error) {
        console.error("Error fetching company details:", error);
      } finally {
        setIsLoading(false);
      }
    }
  };
  const fetchRating = async (id: number) => {
    setIsLoading(true);
    if (id) {
      try {
        const resp = (await useGetCompanyRating(id)) as Rating;
        setReview(resp);
      } catch (error) {
        console.error("Error fetching company rating:", error);
      } finally {
        setIsLoading(false);
      }
    }
  };
  useEffect(() => {
    getCompanyDetails();
    getJobList();
    fetchRating(Number(id));
    return () => {
      setEmployersInfo({} as Company);
    };
  }, [id]);

  useEffect(() => {
    console.log("Fetching photo>>>>", employer?.profilePictureUrl);
  }, [employer]);

  const [ratingValue, setRatingVlaue] = useState<number | null>(null);

  useEffect(() => {
    console.info("ratingValue>>>>>.. ", ratingValue)
  }, [ratingValue])
  const {
    register,
    formState: { errors },
    handleSubmit,
    control
  } = useForm();
  const closeRatingModal = useRef<HTMLButtonElement>(null);

  const handleRatingSubmit = async (data: any) => {
    setIsLoading(true);
    try {
      const { resp, status } = (await useRateCompany(
        id as unknown as number,
        ratingValue!,
        data.ratingReview
      )) as unknown as Response;
      if (status == 200) {
        setIsLoading(false);
        await Swal.fire({
          title: "Success!",
          text: "Company Rated Successfully!",
          icon: "success",
          confirmButtonColor: "#055875",
          iconColor: "#055875",
        });
        closeRatingModal.current?.click();
      }
    } catch (err: any) {
      setIsLoading(false);
      await Swal.fire({
        title: "Failed!",
        text: `${err.resp.error}`,
        icon: "warning",
        confirmButtonColor: "#055875",
        iconColor: "#055875",
      });
      closeRatingModal.current?.click();
      // router.push('')
    } finally {
      setIsLoading(false);
      router.reload();
    }
  };

  return (
    <>
      <Seo pageTitle="Company Profile" />
      {getIsLoading && <UseFullScreenLoader text={"Please Hang On..."} />}
      {/* <!-- Header Span --> */}
      <span className="header-span"></span>

      {/* End Login Popup Modal */}

      <DefaulHeader2 />
      {/* <!--End Main Header --> */}

      <MobileMenu />
      {/* End MobileMenu */}

      {/* <!-- Job Detail Section --> */}
      <section className="job-detail-section">
        {/* <!-- Upper Box --> */}
        <div className="upper-box">
          <div className="auto-container">
            <div className="job-block-seven">
              <div className="inner-box">
                <div className="content">
                  <span className="company-logo">
                    {/* <img src="/images/human_capital_logo.png" alt="logo" /> */}
                    <img src={employer?.profilePictureUrl} alt="" />
                  </span>
                  <div className="d-flex gap-5">
                    <h4>{employer?.name}</h4>
                  </div>

                  <ul className="job-info">
                    {/* <li>
                        <span className="icon flaticon-map-locator"></span>
                        {employer?.location}
                      </li> */}
                    {/* compnay info */}
                    {/* <li>
                        <span className="icon flaticon-briefcase"></span>
                        {employer?.jobType}
                      </li> */}
                    {/* location info */}
                    <li>
                      <a href={`tel:${employer?.contactPhone}`}>
                        <span className="icon flaticon-telephone-1"></span>
                        {employer?.contactPhone}
                      </a>
                    </li>
                    {/* time info */}
                    <li>
                      <a href={`mailto:${employer?.contactEmail}`}>
                        <span className="icon flaticon-mail pe-3"></span>
                        {employer?.contactEmail}
                      </a>
                    </li>
                    {/* salary info */}
                  </ul>
                  {/* End .job-info */}
                </div>
                {/* End .content */}
                <div className="btn-box gap-2">
                  <button
                    className="theme-btn "
                    data-bs-toggle="modal"
                    data-bs-target="#rateEmployer"
                  >
                    {review && <Rating review={review} />}
                  </button>
                  <button
                    className="theme-btn btn-style-one"
                    data-bs-toggle="modal"
                    data-bs-target="#privateMessage"
                  >
                    Private Message
                  </button>
                </div>
                {/* End btn-box */}

                {/* <!-- Modal --> */}
                <div
                  className="modal fade"
                  id="privateMessage"
                  tabIndex={1}
                  aria-hidden="true"
                >
                  <div className="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                    <div className="apply-modal-content modal-content">
                      <div className="text-center">
                        <h3 className="title">
                          Send message to {employer?.name}
                        </h3>
                        <button
                          type="button"
                          className="closed-modal"
                          data-bs-dismiss="modal"
                          aria-label="Close"
                        ></button>
                      </div>
                      {/* End modal-header */}

                      <PrivateMessageBox employer={employer!} />
                      {/* End PrivateMessageBox */}
                    </div>
                    {/* End .send-private-message-wrapper */}
                  </div>
                </div>
                {/* End .modal */}

                {/* <!-- employer rating Modal --> */}
                <div
                  className="modal fade"
                  id="rateEmployer"
                  tabIndex={1}
                  aria-hidden="true"
                >
                  <form onSubmit={handleSubmit(handleRatingSubmit)}>
                    <div className="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                      <div className="apply-modal-content modal-content">
                        <div className="text-center">
                          <h3 className="title">Review {employer?.name}</h3>
                          <Controller
                            control={control}
                            name="rateCompany"
                            rules={{ required: ratingValue == null }}
                            render={({ field: { onChange, onBlur, value, ref } }) => (
                              <RatingModalCompany setRatingVlaue={setRatingVlaue} />
                            )}
                          />
                          {errors.rateCompany &&
                            errors.rateCompany.type == "required" && (
                              <p className="text-danger">
                                Please select a rating
                              </p>
                            )}
                          <div className="form-group">
                            <textarea
                              id=""
                              rows={3}
                              placeholder="Share details of your own experience at this place"
                              className="form-control"
                              {...register("ratingReview", {
                                required: true,
                              })}
                            ></textarea>
                            {errors.ratingReview &&
                              errors.ratingReview.type == "required" && (
                                <p className="text-danger">
                                  Please write a review
                                </p>
                              )}
                          </div>
                          <button
                            className="theme-btn btn-style-one mt-2 mb-1"
                            type="submit"
                          >
                            Post Review
                          </button>
                          <button
                            type="button"
                            className="closed-modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                          ></button>
                          <button
                            ref={closeRatingModal}
                            type="button"
                            className="closed-modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                          ></button>
                        </div>
                        <div className="modal-body p-0">
                          {review?.data.map((review, index) => (
                            <Comments
                              reviewText={review.review}
                              reviewerName={
                                review?.candidate?.firstName! || "Inactive User"
                              }
                              reviewerImage={
                                review?.candidate?.profilePictureUrl!
                              }
                              rating={review.rating}
                              key={index}
                            />
                          ))}
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
                {/* End .modal */}
              </div>
            </div>
            {/* <!-- Job Block --> */}
          </div>
        </div>
        {/* <!-- Upper Box --> */}

        {/* <!-- job-detail-outer--> */}
        <div className="job-detail-outer">
          <div className="auto-container">
            <div className="row">
              <div className="content-column col-lg-8 col-md-12 col-sm-12">
                {/*  job-detail */}
                <div className="job-detail">
                  <div
                    dangerouslySetInnerHTML={{ __html: employer?.description! }}
                  ></div>
                </div>

                <div className="related-jobs">
                  <div className="title-box mt-3">
                    <h3>{jobList.length} job(s) available</h3>
                  </div>
                  <InfiniteScroll
                    dataLength={jobList!.length}
                    next={getJobList}
                    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>
                    }
                  >
                    {jobList.map((job) => (
                      <JobBlock handleSaveJob={handleSaveJob} jobs={job} />
                    ))}
                  </InfiniteScroll>
                </div>
              </div>

              <div className="sidebar-column col-lg-4 col-md-12 col-sm-12">
                <aside className="sidebar">
                  <div className="sidebar-widget company-widget">
                    <div className="widget-content">
                      {/*  compnay-info */}
                      <ul className="company-info mt-0">
                        <li>
                          Phone:{" "}
                          <a href={`tel:${employer?.contactPhone}`}>
                            <span>{employer?.contactPhone}</span>
                          </a>
                        </li>
                        <li>
                          Email:
                          <a
                            className="text-white"
                            href={`mailto:${employer?.contactEmail}`}
                          >
                            <span className="icon flaticon-mail pe-1"></span>
                            {employer?.contactEmail}
                          </a>
                        </li>
                        {/* <li>
                            Location: <span>{employer?.location}</span>
                          </li> */}
                      </ul>
                      {/* End company-info */}

                      <div className="btn-box mt-4">
                        <a
                          href={employer?.website}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="w-100  text-center hc_button d-block"
                        >
                          {employer?.name}
                        </a>
                      </div>
                      {/* btn-box */}
                    </div>
                  </div>

                  {/* End company-widget */}
                </aside>
                {/* End .sidebar */}
              </div>
              {/* End .sidebar-column */}
            </div>
          </div>
        </div>
        {/* <!-- job-detail-outer--> */}
      </section>
      {/* <!-- End Job Detail Section --> */}

      <Footer />
      {/* <!-- End Main Footer --> */}
    </>
  );
};

export default dynamic(() => Promise.resolve(EmployersSingleV1), {
  ssr: false,
});
