import { useForm } from "react-hook-form";
import {
  useCreateMessageConversation,
  useGetCompanyProfileDetails,
  useGetJobDetails,
  useRecommendedJobs,
  useSendMessages,
} from "../../utils/hooks";
import Swal from "sweetalert2";
import { useRouter } from "next/router";
import { useGetPostedJobs } from "../../utils/hooks/useGetPostedJobs";
import { useEffect, useState } from "react";
import { GoogleGenAI } from "@google/genai";
import { useCheckSubscriptionStatus } from "../../utils/hooks/useCheckSubscriptionStatus";
import { AxiosResponse } from "axios";
import { useAuth } from "../../contexts/auth";
import { UserRole } from "../..";
import { useGetCandidateProfileDetails } from "../../utils/hooks/useGetCandidateProfileDetails";
import useGenerateAIResponse from "../../utils/hooks/useGenerateAIResponse";

interface SubscriptionResponse {
  has_active_subscription: boolean;
  expiry_date: string | null;
}

const PrivateMessageBox = ({ employer }: { employer: any }) => {
  const {
    register,
    setValue,
    getValues,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<{ message: string }>();

  const router = useRouter();
  const { userRole } = useAuth() as unknown as UserRole;
  const [companyProfile, setCompanyProfile] = useState<CompanyProfileDetails>();
  const [candidateProfile, setCandidateProfile] =
    useState<CandidateProfileDetails>();
  const [isSubscribed, setIsSubscribed] = useState(false);
  const [jobs, setJobs] = useState<any>([]);
  const [jobDetails, setJobDetails] = useState<any>(null);
  const [isGenerating, setIsGenerating] = useState<boolean>(false);
  const [isSending, setIsSending] = useState<boolean>(false);

  // Helper function to clean up all modals and backdrops
  const cleanupModals = () => {
    // Remove all modal backdrops
    const backdrops = document.querySelectorAll(".modal-backdrop");
    backdrops.forEach((backdrop) => backdrop.remove());

    // Remove all open modals
    const modals = document.querySelectorAll(".modal.show");
    modals.forEach((modal) => {
      modal.classList.remove("show");
      (modal as HTMLElement).style.display = "none";
    });

    // Reset body styles
    document.body.classList.remove("modal-open");
    document.body.style.overflow = "";
    document.body.style.paddingRight = "";
  };

  // Preserve natural line breaks when sending message
  const handleSendPrivateMessage = async ({ message }: { message: string }) => {
    console.log(employer.userId, message);

    // Keep the message exactly as typed (preserve \n)
    const formattedMessage = message.trim();

    setIsSending(true);

    try {
      const { status, data } = (await useCreateMessageConversation(
        employer.userId
      ).catch((err) => err)) as CreateConversationResp;

      if (data?.success !== undefined && !data?.success) {
        const ok = await Swal.fire({
          title: "Conversation already exists!",
          text: "Click ok to go to Messages window to chat with the person/employer",
          icon: "info",
        });
        if (ok.isConfirmed) {
          cleanupModals();
          router.push("/dashboard/messages");
        }
      } else {
        // Make sure message is sent exactly as entered (no format loss)
        const sendMessage = (await useSendMessages(
          formattedMessage,
          data.id!
        )) as any;

        if (sendMessage) {
          await Swal.fire({
            title: "Success!",
            text: "Message Sent Successfully!",
            icon: "success",
          });
          cleanupModals();
          router.push("/dashboard/messages");
        }
      }
    } catch (error) {
      await Swal.fire({
        title: "Error!",
        text: "Failed to send message. Please try again.",
        icon: "error",
      });
      console.error("Error sending message:", error);
    } finally {
      setIsSending(false);
    }
  };

  const FetchUserDetails = async () => {
    if (userRole === "Company") {
      const { resp } =
        (await useGetCompanyProfileDetails()) as CompanyProfileDetailsResp;
      setCompanyProfile(resp);
    }
    if (userRole === "Candidate") {
      const { resp } =
        (await useGetCandidateProfileDetails()) as CandidateProfileDetailsResp;
      setCandidateProfile(resp);
    }
  };

  useEffect(() => {
    FetchUserDetails();
  }, []);

  useEffect(() => {
    FetchPostedJobs();
  }, [employer]);

  useEffect(() => {
    checkSubscriptionStatus();
  }, []);

  const checkSubscriptionStatus = async () => {
    const response = await useCheckSubscriptionStatus();
    const { data } = response as AxiosResponse<SubscriptionResponse>;
    const hasActiveSubscription = data.has_active_subscription;
    if (hasActiveSubscription) {
      setIsSubscribed(true);
    }
  };

  const FetchPostedJobs = async () => {
    if (!employer) return;

    try {
      if (userRole === "Company") {
        const { resp } = (await useGetPostedJobs("/?page=1", "desc")) as any;
        setJobs(resp);
      }
      if (userRole === "Candidate") {
        const { resp } = (await useRecommendedJobs(
          "/?page=1",
          "desc",
          `${employer?.name}`
        )) as any;

        const jobsArray: Job[] = Array.isArray(resp) ? resp : (resp.data ?? []);
        setJobs(jobsArray);
      }
    } catch (error) {
      console.error("Error fetching jobs:", error);
    }
  };

  const handleGetJobDetails = async (id: string) => {
    const { resp } = (await useGetJobDetails(id)) as JobDetailsResp;
    setJobDetails(resp);
  };

  const handleGenerateImpressiveMessageViaAI = async () => {
    if (!isSubscribed) {
      const { value: exp } = await Swal.fire({
        title: "Subscription Required",
        text: "You need to subscribe to get access to this feature",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Subscribe",
        cancelButtonText: "Cancel",
      });

      if (exp) {
        // Clean up all modals before navigation
        cleanupModals();

        // Use setTimeout to ensure cleanup completes before navigation
        setTimeout(() => {
          router.push("/subscription");
        }, 100);

        return;
      } else {
        return;
      }
    }

    const candidate = employer.firstName + " " + employer.lastName;
    const candidateSkill = employer.skills
      .map((skill: any) => skill.name)
      .join(", ");
    const candidateSummary = employer.summary;
    const company = jobDetails.company.name;
    const jobTitle = jobDetails.title;
    const responsibilities = jobDetails.responsibilitiesAndDuties;
    const location = jobDetails.location;
    const jobType = jobDetails.employmentTypes
      .map((type: any) => type.name)
      .join(", ");

    try {
      setIsGenerating(true);

      const prompt = `You are an employer of ${company}. You are reaching out to a candidate for the first time.
        Write a short, friendly, and professional first message.

        Company: ${companyProfile?.name}
        Candidate Name: ${candidate}
        Candidate Skills: ${candidateSkill}
        Candidate Summary: ${candidateSummary}
        Job Title: ${jobTitle}
        Job Responsibilities: ${responsibilities}
        Job Location: ${location}
        Job Type: ${jobType}

        The message should:
        - Be under 150 words
        - Start with a greeting using the candidate's name
        - Mention why their profile is relevant
        - Introduce the job role briefly
        - Invite them to reply or ask questions`;

      const message = (await useGenerateAIResponse(prompt)) as string;

      // preserve newlines from AI output
      setValue("message", message.replace(/\r?\n/g, "\n"));
    } catch (error) {
      console.error("Error generating message:", error);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleGenerateProfessionalMessageViaAI = async () => {
    if (!isSubscribed) {
      const { value: exp } = await Swal.fire({
        title: "Subscription Required",
        text: "You need to subscribe to get access to this feature",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Subscribe",
        cancelButtonText: "Cancel",
      });

      if (exp) {
        // Clean up all modals before navigation
        cleanupModals();

        // Use setTimeout to ensure cleanup completes before navigation
        setTimeout(() => {
          router.push("/subscription");
        }, 100);

        return;
      } else {
        return;
      }
    }

    const company = employer.name;
    const companyDescription = employer.description;
    const jobTitle = jobDetails.title;
    const responsibilities = jobDetails.responsibilitiesAndDuties;
    const location = jobDetails.location;
    const jobType = jobDetails.employmentTypes
      .map((type: any) => type.name)
      .join(", ");

    try {
      setIsGenerating(true);

      const prompt = `You are a candidate writing the first message to a company regarding a job opening.
        Write a short, friendly, and professional message.

        Candidate Name: ${
          candidateProfile?.firstName + " " + candidateProfile?.lastName
        }
        Candidate Skills: ${candidateProfile?.skills
          ?.map((skill: any) => skill.name)
          .join(", ")}
        Candidate Summary: ${employer.summary}

        Company Name: ${company}
        Company Description: ${companyDescription}
        Job Title: ${jobTitle}
        Job Responsibilities: ${responsibilities}
        Job Location: ${location}
        Job Type: ${jobType}

        The message should:
        - Be under 150 words
        - Start with a greeting to the hiring team
        - Mention why you are interested in the role
        - Highlight relevant skills or experience briefly
        - Express enthusiasm and invite next steps or a reply`;

      const message = (await useGenerateAIResponse(prompt)) as string;

      // preserve newlines from AI output
      setValue("message", message.replace(/\r?\n/g, "\n"));
    } catch (error) {
      console.error("Error generating candidate message:", error);
    } finally {
      setIsGenerating(false);
    }
  };

  return (
    <form
      className="default-form"
      onSubmit={handleSubmit(handleSendPrivateMessage)}
    >
      <div className="row">
        <div className="col-lg-12 col-md-12 col-sm-12 form-group">
          <textarea
            className="darma"
            placeholder="Message"
            {...register("message", {
              required: true,
            })}
            style={{ whiteSpace: "pre-line" }}
          ></textarea>
          {errors.message && errors.message.type === "required" && (
            <span className="text-danger">Message is required</span>
          )}
        </div>

        <div className="col-lg-12 col-md-12 col-sm-12 form-group">
          <select
            className="form-select"
            onChange={(e) => handleGetJobDetails(e.target.value)}
          >
            <option value="">Select Job</option>
            {jobs?.map((job: any) => (
              <option key={job.id} value={job.id}>
                {job.title}
              </option>
            ))}
          </select>

          {jobDetails ? (
            isGenerating ? (
              <button className="theme-btn btn-style-one mt-3 w-100" disabled>
                Generating...
              </button>
            ) : (
              <button
                onClick={
                  userRole === "Company"
                    ? handleGenerateImpressiveMessageViaAI
                    : handleGenerateProfessionalMessageViaAI
                }
                className="theme-btn btn-style-one mt-3 w-100"
              >
                {userRole === "Company"
                  ? "Generate Impressive Message via AI"
                  : "Generate Professional Message via AI"}
              </button>
            )
          ) : (
            <button className="theme-btn btn-style-one mt-3 w-100" disabled>
              {userRole === "Company"
                ? "Generate Impressive Message via AI"
                : "Generate Professional Message via AI"}
            </button>
          )}
        </div>

        <div className="col-lg-12 col-md-12 col-sm-12 form-group">
          <button
            className="theme-btn btn-style-one w-100"
            type="submit"
            name="submit-form"
            disabled={isSending}
          >
            {isSending ? "Sending..." : "Send Message"}
          </button>
        </div>
      </div>
    </form>
  );
};

export default PrivateMessageBox;
