import BreadCrumb from "../../../components/dashboard/common/BreadCrumb";
import CopyrightFooter from "../../../components/dashboard/common/CopyrightFooter";
import Seo from "../../../components/common/Seo";
import { useState, useEffect } from "react";
import { useRouter } from "next/router";
import { useSkillApi } from "../../../utils/hooks/useSkillApi";
import { useAuth } from "../../../contexts/auth";
import { useGetCandidateDetails } from "../../../utils/hooks/useGetCandidateDetails";
import Link from "next/link";

const SkillResult = () => {
  const [getIsSidebarOpen, setIsSidebarOpen] = useState(false);
  const [percentage, setPercentage] = useState<number | null>(null);
  const [resultData, setResultData] = useState<any>(null);
  const [candidateName, setCandidateName] = useState<string>("Candidate");
  const [examData, setExamData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();
  const { getResult, getTest, getResults } = useSkillApi() as any;
  const { isAuthenticated, loading: authLoading, user } = useAuth() as any;

  const { performanceId } = router.query;

  // Separate useEffect for authentication check
  // useEffect(() => {
  //   if (authLoading) return;

  //   if (!isAuthenticated) {
  //     router.push("/login");
  //   }
  // }, [authLoading, isAuthenticated, router]);

  // Separate useEffect for data fetching
  // useEffect(() => {
  //   // Don't fetch if still checking auth or not authenticated
  //   if (authLoading || !isAuthenticated) return;
  //   if (!router.isReady) return;
  //   if (resultData) return; // Prevent refetching if we already have data

  //   const fetchData = async () => {
  //     try {
  //       setLoading(true);

  //       const { performanceId, resultId } = router.query;
  //       let result = null;

  //       // Try to fetch by resultId first, then performanceId
  //       if (resultId) {
  //         console.log("Fetching result by resultId:", resultId);
  //         result = await getResult(resultId);
  //       } else if (performanceId) {
  //         console.log("Fetching result by performanceId:", performanceId);
  //         result = await getResult(performanceId);
  //       } else {
  //         // No specific ID, get the most recent result
  //         console.log("No specific ID, fetching most recent result");
  //         const allResults = await getResults();
  //         if (allResults && allResults.length > 0) {
  //           // Sort by endTime descending to get the most recent
  //           const sortedResults = allResults.sort(
  //             (a: any, b: any) =>
  //               new Date(b.endTime || b.end_time).getTime() -
  //               new Date(a.endTime || a.end_time).getTime()
  //           );
  //           result = sortedResults[0];
  //         }
  //       }

  //       if (result) {
  //         console.log("Fetched result:", result);
  //         setResultData(result);

  //         // Calculate percentage from score (e.g., "2 / 2" -> 100%)
  //         if (result.score && typeof result.score === "string") {
  //           const scoreMatch = result.score.match(/(\d+)\s*\/\s*(\d+)/);
  //           if (scoreMatch) {
  //             const obtained = parseInt(scoreMatch[1]);
  //             const total = parseInt(scoreMatch[2]);
  //             const calculatedPercentage =
  //               total > 0 ? (obtained / total) * 100 : 0;
  //             setPercentage(calculatedPercentage);
  //           }
  //         }

  //         // Fetch exam details
  //         const examIdToFetch = result.examId || result.exam_id;
  //         if (examIdToFetch) {
  //           try {
  //             console.log("Fetching exam details for examId:", examIdToFetch);
  //             const exam = await getTest(examIdToFetch);
  //             console.log("Exam data:", exam);
  //             setExamData(exam);
  //           } catch (examErr) {
  //             console.warn("Failed to fetch exam details:", examErr);
  //             setExamData(null);
  //           }
  //         }
  //       } else {
  //         console.warn("No result data found");
  //         setResultData({
  //           score: "Not available",
  //           candidateName: user?.name || user?.firstName || "Candidate",
  //         });
  //       }
  //     } catch (err: any) {
  //       console.error("Failed to load result:", err);
  //       setResultData({
  //         score: "Not available",
  //         candidateName: user?.name || user?.firstName || "Candidate",
  //       });
  //     } finally {
  //       setLoading(false);
  //     }
  //   };

  //   fetchData();
  // }, [
  //   router.isReady,
  //   router.query,
  //   authLoading,
  //   isAuthenticated,
  //   resultData,
  //   getResult,
  //   getResults,
  //   getTest,
  //   user,
  // ]);

  // Fetch result data based on performanceId
  useEffect(() => {
    if (!router.isReady) return;
    if (!performanceId) return;
    const fetchData = async () => {
      try {
        setLoading(true);
        if (performanceId) {
          const result = await getResult(performanceId as string);
          if (result) {
            console.log("Fetched result:", result);
            setResultData(result.performance);
          }
        }
        setLoading(false);
      } catch (err: any) {
        console.error("Failed to load result:", err);
        setResultData({
          score: "Not available",
          candidateName: user?.name || user?.firstName || "Candidate",
        });
      }
    };
    fetchData();
  }, [router.isReady, performanceId]);

  // Fetch candidate name when resultData is available
  useEffect(() => {
    if (resultData) {
      console.log("Candidate ID:", resultData.candidateId);
      const fetchCandidateName = async () => {
        try {
          const { resp } = (await useGetCandidateDetails(
            resultData.candidateId,
          )) as CandidateProfileDetailsResp;
          if (resp) {
            console.log("Candidate data:", resp);
            const firstName = resp.firstName || "";
            const lastName = resp.lastName || "";
            const fullName = `${firstName} ${lastName}`.trim();
            setCandidateName(fullName || "Candidate");
          }
        } catch (err: any) {
          console.error("Failed to fetch candidate name:", err);
        }
      };
      fetchCandidateName();
    }
  }, [resultData]);

  // Format date time
  const formatDateTime = (dateString: string) => {
    if (!dateString) return "N/A";
    try {
      const date = new Date(dateString);
      return date.toLocaleString("en-US", {
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateString;
    }
  };

  // Calculate time taken
  // const getTimeTaken = () => {
  //   if (!resultData?.startTime || !resultData?.endTime) return "N/A";
  //   try {
  //     const start = new Date(resultData.startTime).getTime();
  //     const end = new Date(resultData.endTime).getTime();
  //     const diffMs = end - start;
  //     const diffMins = Math.floor(diffMs / 60000);
  //     const diffSecs = Math.floor((diffMs % 60000) / 1000);
  //     return `${diffMins}m ${diffSecs}s`;
  //   } catch {
  //     return "N/A";
  //   }
  // };

  if (authLoading || !isAuthenticated) {
    return (
      <div className="page-wrapper min-vh-100 d-flex align-items-center justify-content-center">
        <div className="text-center">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <Seo pageTitle="Skill Test Result" />
      <div className="page-wrapper psychometric_test_outer_wrapper result-wrapper min-vh-100">
        <div className="container">
          <section className="user-dashboard">
            <div className="dashboard-outer">
              <BreadCrumb
                title="Skill Test Result"
                getIsSidebarOpen={getIsSidebarOpen}
                setIsSidebarOpen={setIsSidebarOpen}
              />
              <div className="row" style={{ marginTop: "50px" }}>
                <div className="col-lg-12">
                  <div className="ls-widget">
                    <div className="tabs-box p-5">
                      <div className="test_result">
                        <h4
                          className="text-center text-white mb-5"
                          style={{ fontSize: "24px", fontWeight: "600" }}
                        >
                          Candidate: {candidateName}
                        </h4>

                        {/* Main Blue Block Container */}
                        <div
                          className="result-content-block p-5"
                          style={{
                            backgroundColor: "#0d5c75",
                            borderRadius: "12px",
                            minHeight: "450px",
                            display: "flex",
                            flexDirection: "column",
                            justifyContent: "space-between",
                          }}
                        >
                          <div className="row align-items-start flex-grow-1">
                            {/* Left Side - Exam Details */}
                            <div
                              className="col-md-4"
                              style={{
                                padding: "20px",
                                backgroundColor: "rgba(63, 224, 208, 0.1)",
                                borderRadius: "12px",
                                border: "1px solid rgba(63, 224, 208, 0.3)",
                              }}
                            >
                              <div className="exam-details text-white">
                                <h5
                                  className="mb-4"
                                  style={{
                                    fontWeight: "600",
                                    fontSize: "20px",
                                  }}
                                >
                                  Exam Details
                                </h5>
                                {loading ? (
                                  <div className="text-white">
                                    Loading exam details...
                                  </div>
                                ) : (
                                  <div className="details-list">
                                    <div className="detail-item mb-4">
                                      <p
                                        className="mb-2 text-white"
                                        style={{
                                          fontSize: "14px",
                                          opacity: "0.8",
                                          fontWeight: "600",
                                        }}
                                      >
                                        Exam Name:
                                      </p>
                                      <p
                                        className="mb-0 text-white"
                                        style={{ fontSize: "16px" }}
                                      >
                                        {examData?.name ||
                                          examData?.title ||
                                          "Skill Exam"}
                                      </p>
                                    </div>

                                    {examData?.description && (
                                      <div className="detail-item mb-4">
                                        <p
                                          className="mb-2 text-white"
                                          style={{
                                            fontSize: "14px",
                                            opacity: "0.8",
                                            fontWeight: "600",
                                          }}
                                        >
                                          Description:
                                        </p>
                                        <p
                                          className="mb-0 text-white"
                                          style={{
                                            fontSize: "14px",
                                            lineHeight: "1.6",
                                          }}
                                        >
                                          {examData.description}
                                        </p>
                                      </div>
                                    )}

                                    {examData?.duration && (
                                      <div className="detail-item mb-4">
                                        <p
                                          className="mb-2 text-white"
                                          style={{
                                            fontSize: "14px",
                                            opacity: "0.8",
                                            fontWeight: "600",
                                          }}
                                        >
                                          Duration:
                                        </p>
                                        <p
                                          className="mb-0 text-white"
                                          style={{ fontSize: "16px" }}
                                        >
                                          {examData.duration} minutes
                                        </p>
                                      </div>
                                    )}

                                    <div className="detail-item mb-4">
                                      <p
                                        className="mb-2 text-white"
                                        style={{
                                          fontSize: "14px",
                                          opacity: "0.8",
                                          fontWeight: "600",
                                        }}
                                      >
                                        Completed On:
                                      </p>
                                      <p
                                        className="mb-0 text-white"
                                        style={{ fontSize: "14px" }}
                                      >
                                        {formatDateTime(resultData?.endTime)}
                                      </p>
                                    </div>

                                    <div className="detail-item mb-4">
                                      <p
                                        className="mb-2 text-white"
                                        style={{
                                          fontSize: "14px",
                                          opacity: "0.8",
                                          fontWeight: "600",
                                        }}
                                      >
                                        Time Taken:
                                      </p>
                                      <p
                                        className="mb-0 text-white"
                                        style={{ fontSize: "16px" }}
                                      >
                                        {resultData?.timeTaken || "N/A"}
                                      </p>
                                    </div>

                                    <div className="detail-item mb-4">
                                      <p
                                        className="mb-2 text-white"
                                        style={{
                                          fontSize: "14px",
                                          opacity: "0.8",
                                          fontWeight: "600",
                                        }}
                                      >
                                        Status:
                                      </p>
                                      <p
                                        className="mb-0 text-white"
                                        style={{
                                          fontSize: "16px",
                                          textTransform: "capitalize",
                                        }}
                                      >
                                        {resultData?.status?.toLowerCase() ||
                                          "N/A"}
                                      </p>
                                    </div>
                                  </div>
                                )}
                              </div>
                            </div>

                            {/* Right Side - Score Details */}
                            <div className="col-md-6 offset-md-1">
                              <div
                                className="score-details text-center"
                                style={{
                                  marginTop: "110px",
                                  padding: "20px",
                                  backgroundColor: "rgba(63, 224, 208, 0.1)",
                                  borderRadius: "12px",
                                  border: "1px solid rgba(63, 224, 208, 0.3)",
                                }}
                              >
                                <h4
                                  className="text-white mb-4"
                                  style={{
                                    fontSize: "22px",
                                    fontWeight: "600",
                                  }}
                                >
                                  Your Score
                                </h4>

                                {/* Score Display */}
                                <div
                                  className="score-display"
                                  style={{
                                    margin: "20px auto 0",
                                    maxWidth: "300px",
                                    textAlign: "center",
                                  }}
                                >
                                  {loading ? (
                                    <div className="text-white">Loading...</div>
                                  ) : (
                                    <>
                                      <div
                                        className="score-numbers text-white"
                                        style={{
                                          fontSize: "72px",
                                          fontWeight: "700",
                                          lineHeight: "1",
                                          letterSpacing: "2px",
                                          marginBottom: "20px",
                                        }}
                                      >
                                        {resultData?.score === "Not available"
                                          ? "No results"
                                          : resultData?.score || "N/A"}
                                      </div>

                                      {percentage !== null && (
                                        <div
                                          className="percentage-display text-white"
                                          style={{
                                            fontSize: "28px",
                                            fontWeight: "600",
                                            color: "#3FE0D0",
                                            marginTop: "10px",
                                          }}
                                        >
                                          {percentage.toFixed(0)}% Correct
                                        </div>
                                      )}

                                      {resultData?.answerSet && (
                                        <div
                                          className="answer-count text-white mt-3"
                                          style={{
                                            fontSize: "16px",
                                            opacity: "0.8",
                                          }}
                                        >
                                          Answered{" "}
                                          {
                                            Object.keys(resultData.answerSet)
                                              .length
                                          }{" "}
                                          questions
                                        </div>
                                      )}
                                    </>
                                  )}
                                </div>
                              </div>
                            </div>
                          </div>

                          {/* Bottom - Skill Development Message */}
                          <div className="row mt-5">
                            <div className="col-12">
                              <div
                                className="skill-message text-white p-4"
                                style={{
                                  backgroundColor: "rgba(63, 224, 208, 0.1)",
                                  borderRadius: "12px",
                                  border: "1px solid rgba(63, 224, 208, 0.3)",
                                }}
                              >
                                <div className="message-content">
                                  <div className="d-flex align-items-center mb-3">
                                    <span
                                      style={{
                                        fontSize: "24px",
                                        marginRight: "12px",
                                      }}
                                    >
                                      🎯
                                    </span>
                                    <h5
                                      className="mb-0"
                                      style={{
                                        fontSize: "18px",
                                        fontWeight: "600",
                                      }}
                                    >
                                      Skill Assessment Complete!
                                    </h5>
                                  </div>

                                  <p
                                    className="mb-3"
                                    style={{
                                      fontSize: "15px",
                                      lineHeight: "1.6",
                                      color: "#f8f9fa",
                                    }}
                                  >
                                    Congratulations on completing your skill
                                    assessment! Your performance demonstrates
                                    your current proficiency level and provides
                                    valuable insights for your professional
                                    development.
                                  </p>

                                  <div className="skill-insights">
                                    <h6
                                      style={{
                                        fontSize: "16px",
                                        fontWeight: "600",
                                        marginBottom: "12px",
                                        color: "#3FE0D0",
                                      }}
                                    >
                                      Key Insights:
                                    </h6>
                                    <ul
                                      style={{
                                        fontSize: "14px",
                                        lineHeight: "1.7",
                                        opacity: "0.9",
                                        paddingLeft: "20px",
                                      }}
                                    >
                                      <li>
                                        <strong>Strength Areas:</strong>{" "}
                                        Continue building on your strong
                                        performance in key competencies
                                      </li>
                                      <li>
                                        <strong>Growth Opportunities:</strong>{" "}
                                        Focus on areas identified for
                                        improvement to enhance your skills
                                      </li>
                                      <li>
                                        <strong>Next Steps:</strong> Consider
                                        targeted training or practice in areas
                                        of development
                                      </li>
                                      <li>
                                        <strong>Career Alignment:</strong> Your
                                        results help identify suitable roles and
                                        career paths
                                      </li>
                                    </ul>
                                  </div>

                                  <div
                                    className="encouragement-text mt-3 pt-3"
                                    style={{
                                      borderTop:
                                        "1px solid rgba(255, 255, 255, 0.2)",
                                      fontStyle: "italic",
                                      textAlign: "center",
                                      opacity: "0.9",
                                    }}
                                  >
                                    <p
                                      className="mb-0"
                                      style={{ color: "#f8f9fa" }}
                                    >
                                      Skills are developed through persistence
                                      and practice. Keep learning, keep growing,
                                      and keep achieving your goals!
                                    </p>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div className="d-flex align-items-center justify-content-center mt-4">
                          <div className="theme-btn btn-style-four cursor-pointer">
                            <Link href="/dashboard/skill-test">
                              <span className="btn-title">Back to Tests</span>
                            </Link>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>

        <CopyrightFooter />
      </div>
    </>
  );
};

export default SkillResult;
