import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Contact from "../../components/candidate/Contact";
import JobSkills from "../../components/candidate/JobSkills";
import Seo from "../../components/common/Seo";
import Social from "../../components/company/Social";
import Footer from "../../components/footer/Footer";
import DefaulHeader2 from "../../components/header/DefaulHeader2";
import MobileMenu from "../../components/header/MobileMenu";
import UseFullScreenLoader from "../../hooks/UseFullScreenLoader";
import { useGetCandidateDetails } from "../../utils/hooks/useGetCandidateDetails";
import PrivateMessageBox from "../../components/company/PrivateMessageBox";
import { useGetVnnStatus } from "../../utils/hooks/useGetVnnStatus";
import { useGetVninProfilePicture } from "../../utils/hooks";
import PhotoComparisonModal from "../../components/VNINVerification/photo-comparison-modal";
import {
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
  ResponsiveContainer,
  Legend,
  Tooltip,
} from "recharts";
import { useSkillApi } from "../../utils/hooks/useSkillApi";
import { usePsychometricApi } from "../../utils/hooks/usePsychometricApi";

interface PsychometricExamResult {
  category: string;
  score: number;
  maxScore: number;
  description: string;
}

const CandidateSingleDynamicV1 = () => {
  const router = useRouter();
  const [candidateProfile, setCandidateProfile] = useState<any>(null);
  const [getIsLoading, setIsLoading] = useState<boolean>(true);
  const candidateId = router.query.candidateId;
  const [getVnnStatus, setVnnStatus] = useState<number>(0);
  const [getLoading, setLoading] = useState<boolean>(false);
  const [images, setImages] = useState<{ candidate: string; vnin: string }>({
    candidate: "",
    vnin: "",
  });
  const [candidateAge, setCandidateAge] = useState<string>("N/A");

  const { getResults } = useSkillApi() as any;
  const { getResults: getPsychometricResults } = usePsychometricApi() as any;

  const [psychometricResults, setPsychometricResults] = useState<
    PsychometricExamResult[]
  >([]);
  const [skillExamResults, setSkillExamResults] = useState<any[]>([]);

  // Exact colors from TestResult page
  const BG_COLOR = "#0d5c75";
  const ACCENT_COLOR = "#3FE0D0";
  const CARD_BG = "rgba(63, 224, 208, 0.1)";
  const CARD_BORDER = "rgba(63, 224, 208, 0.3)";

  const FetchVnnStatus = async (id: number) => {
    try {
      const { resp, status } = (await useGetVnnStatus(id)) as any;
      if (status === 200) setVnnStatus(resp.isVerified);
    } catch (error) {
      console.error("Error fetching Vnn Status:", error);
    }
  };

  useEffect(() => {
    candidateProfile?.userId && FetchVnnStatus(candidateProfile?.userId);
  }, [candidateProfile]);

  const calculateAge = (dateOfBirth: string | undefined): string => {
    if (!dateOfBirth) return "N/A";
    try {
      const birthDate = new Date(dateOfBirth);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      if (
        monthDiff < 0 ||
        (monthDiff === 0 && today.getDate() < birthDate.getDate())
      )
        age--;
      return `${age} Years`;
    } catch {
      return "N/A";
    }
  };

  const FetchCandidateDetails = async () => {
    if (!candidateId) return;
    try {
      console.log("candidate id>>>>>>", candidateId);
      const { resp } = (await useGetCandidateDetails(
        Number(candidateId)
      )) as any;
      setCandidateProfile(resp);
      if (resp?.dateOfBirth) {
        setCandidateAge(calculateAge(resp.dateOfBirth));
      }
    } catch (error) {
      console.error("Error fetching candidate details", error);
    } finally {
      setIsLoading(false);
    }
  };

  const FetchPsychometricResults = async () => {
    try {
      const result = await getPsychometricResults(candidateId as string);
      if (!result || result.length === 0) {
        setPsychometricResults([]);
        return;
      }
      const exam = result[0];
      const parsedScore = JSON.parse(exam.score);
      const mapped = Object.entries(parsedScore).map(([category, score]) => ({
        category,
        score: Number(score),
        maxScore: 7,
        description: "",
      }));
      setPsychometricResults(mapped);
    } catch (error) {
      console.error("Error fetching psychometric results:", error);
      setPsychometricResults([]);
    }
  };

  const FetchSkillExamResults = async () => {
    if (!candidateId) return;
    try {
      const result = await getResults(candidateId as string);
      if (result) {
        const mapped = result.map((item: any) => ({
          skillName: item.examRole,
          score: item.score,
          maxScore: item.maxScore,
          percentage: item.percentage,
          completedDate: item.endTime?.split("T")[0],
          status: item.status,
        }));
        setSkillExamResults(mapped);
      }
    } catch (error) {
      console.error("Error fetching skill exam results:", error);
    }
  };

  useEffect(() => {
    setIsLoading(true);
    FetchCandidateDetails();
    FetchPsychometricResults();
    FetchSkillExamResults();
  }, [candidateId]);

  const FetchVninProfilePicture = async () => {
    try {
      setLoading(true);
      const { resp } = (await useGetVninProfilePicture(
        Number(candidateId)
      )) as any;
      const profilePicture =
        resp.candidate_profile_picture[0]?.profilePictureUrl;
      const vninPicture = resp.vnin_profile_picture[0]?.vninProfilePicture;
      setImages({ candidate: profilePicture, vnin: vninPicture });
    } catch (error) {
      console.log("Error fetching pictures", error);
    } finally {
      setLoading(false);
    }
  };

  const radarChartData = psychometricResults.map((item) => ({
    category: item.category,
    score: item.score,
    fullMark: 7,
  }));

  return (
    <>
      {getIsLoading && <UseFullScreenLoader text="Please Hang On..." />}
      <Seo pageTitle="Candidate Profile" />

      <span className="header-span"></span>
      <DefaulHeader2 />
      <MobileMenu />

      <section className="candidate-detail-section">
        <div className="upper-box">
          <div className="auto-container">
            <div className="candidate-block-five">
              <div className="inner-box">
                <div className="content">
                  <figure className="image">
                    <img
                      style={{
                        objectFit: "contain",
                        width: "100%",
                        height: "100%",
                        maxWidth: "150px",
                        maxHeight: "150px",
                      }}
                      src={
                        candidateProfile?.profilePictureUrl ||
                        "/images/human_capital_logo.png"
                      }
                      alt="candidate"
                      onError={(e) => {
                        e.currentTarget.src = "/images/human_capital_logo.png";
                        e.currentTarget.onerror = null;
                      }}
                    />
                  </figure>
                  <div className="d-flex align-items-center gap-3">
                    <h4 className="name">
                      {candidateProfile?.firstName} {candidateProfile?.lastName}
                    </h4>
                    {getVnnStatus ? (
                      <div
                        onClick={FetchVninProfilePicture}
                        data-bs-toggle="modal"
                        data-bs-target="#photoComparisonModal"
                        style={{ cursor: "pointer" }}
                      >
                        <p className="text-success d-flex align-items-center gap-1">
                          <img
                            src="/images/verified.svg"
                            width={20}
                            height={20}
                            alt="verified"
                          />
                          VNIN Verified
                        </p>
                        <PhotoComparisonModal
                          profilePicture={images.candidate}
                          vninPicture={images.vnin}
                          getLoading={getLoading}
                        />
                      </div>
                    ) : null}
                  </div>
                  <ul className="candidate-info">
                    <li className="designation">
                      {candidateProfile?.pronouns || ""}
                    </li>
                    <li>
                      <span className="icon flaticon-map-locator"></span>
                      {[
                        candidateProfile?.city,
                        candidateProfile?.state,
                        candidateProfile?.country,
                      ]
                        .filter(Boolean)
                        .join(", ") || "Not available"}
                    </li>
                  </ul>
                </div>

                <div className="btn-box">
                  {localStorage.getItem("profileType") === "Candidate" && (
                    <button
                      className="theme-btn btn-style-one"
                      onClick={() => router.push("/dashboard/profile")}
                    >
                      Edit Profile
                    </button>
                  )}
                  {localStorage.getItem("profileType") === "Company" && (
                    <button
                      className="theme-btn btn-style-one"
                      data-bs-toggle="modal"
                      data-bs-target="#privateMessage"
                    >
                      Private Message
                    </button>
                  )}
                  <div className="modal fade" id="privateMessage" tabIndex={-1}>
                    <div className="modal-dialog modal-dialog-centered">
                      <div className="apply-modal-content modal-content">
                        <div className="text-center">
                          <h3 className="title">
                            Send message to {candidateProfile?.firstName}
                          </h3>
                          <button
                            type="button"
                            className="closed-modal"
                            data-bs-dismiss="modal"
                          ></button>
                        </div>
                        <PrivateMessageBox employer={candidateProfile!} />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="candidate-detail-outer">
          <div className="auto-container">
            <div className="row">
              <div className="content-column col-lg-8 col-md-12 col-sm-12">
                <div className="job-detail">
                  {candidateProfile?.summary &&
                    candidateProfile.summary !== "<p><br/></p>" && (
                      <div className="job-detail-sub-section">
                        <h4>About</h4>
                        <div
                          dangerouslySetInnerHTML={{
                            __html: candidateProfile.summary,
                          }}
                          className="list-style-three"
                        />
                      </div>
                    )}

                  {/* Skill Exam Results */}
                  {skillExamResults.length > 0 && (
                    <div className="job-detail-sub-section mb-5">
                      <h4
                        className="mb-4"
                        style={{ color: "#115a7c", fontWeight: "600" }}
                      >
                        Skill Exam Results
                      </h4>

                      <div className="table-responsive">
                        <table
                          className="table table-striped table-hover"
                          style={{
                            borderRadius: "12px",
                            overflow: "hidden",
                            boxShadow: "0 4px 12px rgba(0,0,0,0.05)",
                          }}
                        >
                          <thead
                            style={{
                              backgroundColor: "#f0f9fb",
                              borderBottom: "2px solid #a0e0e0",
                            }}
                          >
                            <tr>
                              <th
                                className="py-3 px-4"
                                style={{
                                  color: "#115a7c",
                                  fontWeight: "600",
                                  fontSize: "15px",
                                }}
                              >
                                Skill
                              </th>
                              <th
                                className="py-3 px-4 text-center"
                                style={{
                                  color: "#115a7c",
                                  fontWeight: "600",
                                  fontSize: "15px",
                                }}
                              >
                                Score
                              </th>
                              <th
                                className="py-3 px-4 text-center"
                                style={{
                                  color: "#115a7c",
                                  fontWeight: "600",
                                  fontSize: "15px",
                                }}
                              >
                                Completed Date
                              </th>
                            </tr>
                          </thead>
                          <tbody>
                            {skillExamResults.map((result, index) => (
                              <tr
                                key={index}
                                style={{
                                  backgroundColor:
                                    index % 2 === 0 ? "#ffffff" : "#f8fdff",
                                }}
                              >
                                <td
                                  className="py-3 px-4"
                                  style={{ fontWeight: "500", color: "#333" }}
                                >
                                  {result.skillName}
                                </td>
                                <td
                                  className="py-3 px-4 text-center"
                                  style={{
                                    color: "#115a7c",
                                    fontWeight: "600",
                                  }}
                                >
                                  {result.score}{" "}
                                  {result.maxScore
                                    ? `/ ${result.maxScore}`
                                    : ""}
                                </td>
                                <td
                                  className="py-3 px-4 text-center"
                                  style={{ color: "#555" }}
                                >
                                  {result.completedDate
                                    ? new Date(
                                        result.completedDate
                                      ).toLocaleDateString("en-US", {
                                        year: "numeric",
                                        month: "long",
                                        day: "numeric",
                                      })
                                    : "—"}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  )}

                  {/* Psychometric Section - Matching TestResult Style Exactly */}
                  {/* Psychometric Section - FIXED Radar Chart: No Cut Text + Perfectly Centered */}
                  {psychometricResults.length > 0 && (
                    <div
                      className="job-detail-sub-section p-5"
                      style={{
                        backgroundColor: BG_COLOR,
                        borderRadius: "12px",
                        marginTop: "40px",
                      }}
                    >
                      <h4
                        className="text-white text-center mb-5"
                        style={{ fontSize: "24px", fontWeight: "600" }}
                      >
                        Psychometric Assessment Results
                      </h4>

                      <div className="row justify-content-center">
                        {/* Radar Chart - Centered and Fixed Clipping */}
                        <div className="col-lg-9 col-md-10 col-12">
                          <div className="category-results text-center">
                            <h5
                              className="text-white mb-4"
                              style={{ fontWeight: "600", fontSize: "20px" }}
                            >
                              Performance Overview
                            </h5>

                            <ResponsiveContainer width="100%" height={480}>
                              <RadarChart
                                data={radarChartData}
                                margin={{
                                  top: 40,
                                  right: 60,
                                  bottom: 40,
                                  left: 60,
                                }} // Increased margins to prevent cut-off
                              >
                                <PolarGrid stroke="rgba(255, 255, 255, 0.3)" />

                                <PolarAngleAxis
                                  dataKey="category"
                                  tick={{
                                    fill: "#ffffff",
                                    fontSize: 13,
                                    fontWeight: 500,
                                  }}
                                  tickLine={false} // Removes lines that can cause overflow
                                />

                                <PolarRadiusAxis
                                  angle={90}
                                  domain={[0, 7]}
                                  tickCount={8}
                                  tick={{ fill: "#ffffff", fontSize: 11 }}
                                  axisLine={{
                                    stroke: "rgba(255, 255, 255, 0.3)",
                                  }}
                                />

                                <Radar
                                  name="Score"
                                  dataKey="score"
                                  stroke={ACCENT_COLOR}
                                  strokeWidth={3}
                                  fill={ACCENT_COLOR}
                                  fillOpacity={0.6}
                                />

                                <Tooltip
                                  contentStyle={{
                                    backgroundColor: BG_COLOR,
                                    border: `1px solid ${ACCENT_COLOR}`,
                                    borderRadius: "8px",
                                    color: "#fff",
                                  }}
                                  formatter={(value: any) => [
                                    `${value} / 7`,
                                    "Score",
                                  ]}
                                />

                                <Legend
                                  verticalAlign="bottom"
                                  wrapperStyle={{
                                    color: "#ffffff",
                                    paddingTop: "20px",
                                  }}
                                  iconType="circle"
                                />
                              </RadarChart>
                            </ResponsiveContainer>
                          </div>
                        </div>
                      </div>

                      {/* Score Breakdown */}
                      <div className="mt-5">
                        <h5
                          className="text-white mb-4"
                          style={{ fontWeight: "600", fontSize: "18px" }}
                        >
                          Score Breakdown
                        </h5>
                        <div className="row">
                          {psychometricResults.map((item, index) => (
                            <div key={index} className="col-md-6 col-lg-4 mb-3">
                              <div
                                style={{
                                  backgroundColor: CARD_BG,
                                  borderRadius: "8px",
                                  border: `1px solid ${CARD_BORDER}`,
                                  padding: "15px",
                                }}
                              >
                                <h6
                                  className="mb-2 text-white"
                                  style={{
                                    fontSize: "14px",
                                    fontWeight: "500",
                                  }}
                                >
                                  {item.category}
                                </h6>
                                <div
                                  className="progress"
                                  style={{ height: "20px" }}
                                >
                                  <div
                                    className="progress-bar"
                                    style={{
                                      width: `${(item.score / 7) * 100}%`,
                                      backgroundColor: ACCENT_COLOR,
                                    }}
                                  >
                                    <span
                                      style={{
                                        fontSize: "12px",
                                        fontWeight: "bold",
                                        color: "#000",
                                      }}
                                    >
                                      {item.score.toFixed(2)} / 7
                                    </span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {psychometricResults.length === 0 && (
                    <div className="text-center py-5 text-muted">
                      <p>
                        No psychometric assessment data available for this
                        candidate.
                      </p>
                    </div>
                  )}
                </div>
              </div>

              {/* Sidebar */}
              <div className="sidebar-column col-lg-4 col-md-12 col-sm-12">
                <aside className="sidebar">
                  <div className="sidebar-widget">
                    <div className="widget-content">
                      <ul className="job-overview">
                        <li>
                          <i className="icon icon-expiry"></i>
                          <h5>Age:</h5>
                          <span>{candidateAge}</span>
                        </li>
                        <li>
                          <i className="icon icon-user-2"></i>
                          <h5>Gender:</h5>
                          <span>
                            {candidateProfile?.gender || "Not specified"}
                          </span>
                        </li>
                      </ul>
                    </div>
                  </div>

                  <div className="sidebar-widget social-media-widget">
                    <h4 className="widget-title">Social Media</h4>
                    <div className="widget-content">
                      <Social />
                    </div>
                  </div>

                  <div className="sidebar-widget">
                    <h4 className="widget-title">Professional Skills</h4>
                    <div className="widget-content">
                      <ul className="job-skills">
                        <JobSkills skills={candidateProfile?.skills || []} />
                      </ul>
                    </div>
                  </div>

                  <div className="sidebar-widget contact-widget">
                    <h4 className="widget-title">Contact</h4>
                    <div className="widget-content">
                      <Contact
                        phone={candidateProfile?.phone}
                        email={candidateProfile?.email}
                        address={candidateProfile?.address}
                        city={candidateProfile?.city}
                        state={candidateProfile?.state}
                        country={candidateProfile?.country}
                      />
                    </div>
                  </div>
                </aside>
              </div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
};

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