import React, { useEffect, useState } from "react";
import BreadCrumb from "../../../components/dashboard/common/BreadCrumb";
import CopyrightFooter from "../../../components/dashboard/common/CopyrightFooter";
import Seo from "../../../components/common/Seo";
import DashboardHeader from "../../../components/header/DashboardHeader";
import DashboardSidebar from "../../../components/header/DashboardSidebar";
import MobileMenu from "../../../components/header/MobileMenu";
import { useSkillApi } from "../../../utils/hooks/useSkillApi";
import { useAuth } from "../../../contexts/auth";
import { useRouter } from "next/router";
import { useGetCandidateProfileDetails } from "../../../utils/hooks/useGetCandidateProfileDetails";

interface SkillTest {
  id: number;
  title: string;
  name?: string;
  description?: string;
  duration?: number;
  role?: string;
  isActive?: boolean;
  companyId?: number | null;
  jobPostId?: number | null;
  skillQuestionLibrary?: {
    id: number;
    title?: string;
  };
}

interface ExamAttempt {
  examId: number;
  endTime: string;
  status: string;
  percentage?: number | null;
}

// Cooldown period in months
const COOLDOWN_MONTHS = 3;

const SkillTestIndex = () => {
  const [getIsSidebarOpen, setIsSidebarOpen] = useState(false);
  const skillApi = useSkillApi() as any;
  const { userRole, isAuthenticated } = useAuth() as any;
  const router = useRouter();
  const [candidateId, setCandidateId] = useState<number | null>(null);

  // Check if user is authenticated and is a candidate
  useEffect(() => {
    if (isAuthenticated && userRole && userRole.toLowerCase() !== "candidate") {
      router.push("/dashboard");
    }
  }, [isAuthenticated, userRole, router]);

  const [exams, setExams] = useState<SkillTest[]>([]);
  const [loadingExams, setLoadingExams] = useState(false);
  const [examsError, setExamsError] = useState<string | null>(null);
  const [examAttempts, setExamAttempts] = useState<Map<number, ExamAttempt>>(
    new Map(),
  );

  // Filter state
  const [searchQuery, setSearchQuery] = useState("");

  // Fetch candidate profile to get candidateId
  useEffect(() => {
    const fetchCandidateProfile = async () => {
      if (!isAuthenticated || userRole?.toLowerCase() !== "candidate") return;

      try {
        const { resp } = (await useGetCandidateProfileDetails()) as any;
        console.log("Fetched candidate profile:", resp);
        if (resp?.id) {
          setCandidateId(resp.id);
        }
      } catch (err) {
        console.error("Failed to fetch candidate profile:", err);
      }
    };

    fetchCandidateProfile();
  }, [isAuthenticated, userRole]);

  // Fetch exam attempts to check cooldown
  useEffect(() => {
    const fetchExamAttempts = async () => {
      if (!candidateId) return;

      try {
        const results = await skillApi.getResults(candidateId);
        console.log("Fetched exam results for cooldown check:", results);

        const parsePercentage = (result: any): number | null => {
          const rawPercentage = result?.percentage;
          if (
            typeof rawPercentage === "number" &&
            Number.isFinite(rawPercentage)
          ) {
            return rawPercentage;
          }

          if (typeof rawPercentage === "string") {
            const cleaned = rawPercentage.trim().replace("%", "");
            const parsed = Number(cleaned);
            if (Number.isFinite(parsed)) {
              return parsed;
            }
          }

          const rawScore = String(result?.score || "");
          const match = rawScore.match(/(\d+)\s*\/\s*(\d+)/);
          if (!match) return null;

          const obtained = Number(match[1]);
          const total = Number(match[2]);
          if (
            !Number.isFinite(obtained) ||
            !Number.isFinite(total) ||
            total <= 0
          ) {
            return null;
          }

          return (obtained / total) * 100;
        };

        // Create a map of examId -> most recent completed attempt
        const attemptsMap = new Map<number, ExamAttempt>();
        if (Array.isArray(results)) {
          results.forEach((result: any) => {
            const examId = Number(result.examId || result.exam_id);
            const endTime = result.endTime || result.end_time;
            const status = result.status;
            const percentage = parsePercentage(result);

            // Track by ID and composite key of title+role
            const title =
              result.examTitle || result.exam?.title || result.exam?.name || "";
            const role = result.examRole || result.exam?.role || "";
            const compositeKey = `${title?.toLowerCase()}_${role?.toLowerCase()}`;

            // Only track COMPLETED exams
            if (status === "COMPLETED" && endTime) {
              const prevAttempt =
                attemptsMap.get(examId) ||
                (compositeKey !== "_"
                  ? attemptsMap.get(compositeKey as any)
                  : null);

              if (
                !prevAttempt ||
                new Date(endTime) > new Date(prevAttempt.endTime)
              ) {
                const attemptData = { examId, endTime, status, percentage };
                if (Number.isFinite(examId) && examId > 0) {
                  attemptsMap.set(examId, attemptData);
                }
                if (compositeKey !== "_") {
                  attemptsMap.set(compositeKey as any, attemptData);
                }
              }
            }
          });
        }
        console.log("Exam attempts map:", attemptsMap);
        setExamAttempts(attemptsMap);
      } catch (err) {
        console.error("Failed to fetch exam attempts:", err);
      }
    };

    fetchExamAttempts();
  }, [candidateId]);

  useEffect(() => {
    const fetchExams = async () => {
      console.log("Current userRole:", userRole);
      setLoadingExams(true);
      try {
        const data: any = await skillApi.getExams();
        console.log("Fetched skill exams data:", data);

        // Handle various response formats
        let examsArray: SkillTest[] = [];
        if (Array.isArray(data)) {
          examsArray = data;
        } else if (data && typeof data === "object") {
          if (Array.isArray(data.data)) {
            examsArray = data.data;
          } else if (Array.isArray(data.exams)) {
            examsArray = data.exams;
          } else if (Array.isArray(data.skillExams)) {
            examsArray = data.skillExams;
          }
        }

        // Filter: Show only active exams that are NOT attached to a job post
        const candidateExams = (examsArray || []).filter((exam: any) => {
          const isActive =
            exam.isActive !== false &&
            exam.isActive !== 0 &&
            exam.isActive !== "0";
          const jobPostId = exam.jobPostId || exam.job_post_id || null;
          const isNotAttachedToJob = !jobPostId;

          console.log(
            `Exam ${exam.id} (${exam.title}): isActive=${isActive}, jobPostId=${jobPostId}, role=${exam.role}`,
          );

          // Show if: active AND not attached to any job
          return isActive && isNotAttachedToJob;
        });

        setExams(candidateExams || []);
      } catch (err: any) {
        console.error("Failed to fetch exams", err);
        setExamsError(
          err?.response?.data?.message ||
            err?.message ||
            "Failed to load exams",
        );
      } finally {
        setLoadingExams(false);
      }
    };

    fetchExams();
  }, []);

  // Check if exam is in cooldown period
  const getExamCooldownInfo = (
    examId: number,
    examTitle: string,
    examRole: string,
  ) => {
    let attempt = examAttempts.get(examId);

    // Fallback to title+role composite key if ID doesn't match
    if (!attempt) {
      const compositeKey = `${(examTitle || "").toLowerCase()}_${(examRole || "").toLowerCase()}`;
      if (compositeKey !== "_") {
        attempt = examAttempts.get(compositeKey as any);
      }
    }

    if (!attempt) {
      return { isInCooldown: false, nextAvailableDate: null };
    }

    const lastAttemptDate = new Date(attempt.endTime);
    const nextAvailableDate = new Date(lastAttemptDate);
    nextAvailableDate.setMonth(nextAvailableDate.getMonth() + COOLDOWN_MONTHS);

    const now = new Date();
    const isInCooldown = now < nextAvailableDate;

    return { isInCooldown, nextAvailableDate, lastAttemptDate };
  };

  // Format date for display
  const formatDate = (date: Date) => {
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  const isEligible = (exam: SkillTest) => {
    // For skill tests available to candidates (not job-specific), candidates should always be eligible
    // These tests are filtered to only show active tests not attached to jobs, so candidates can take them
    // If user is not authenticated or not a candidate, not eligible
    if (!userRole || String(userRole).toLowerCase() !== "candidate") {
      console.log(`- Result: NOT ELIGIBLE (user is not a candidate)`);
      return false;
    }
    return true;
  };

  // Filter exams based on search query
  const filteredExams = exams.filter((exam) => {
    if (!searchQuery.trim()) return true;

    const query = searchQuery.toLowerCase().trim();
    const title = (exam.title || exam.name || "").toLowerCase();
    const subject = (
      exam.skillQuestionLibrary?.title ||
      exam.role ||
      ""
    ).toLowerCase();

    // Search across title and subject
    return title.includes(query) || subject.includes(query);
  });

  const handleStartTest = (exam: SkillTest) => {
    // Navigate to rules page first, then start exam
    router.push(`/dashboard/skill-test/startexam?examId=${exam.id}`);
  };

  return (
    <>
      <Seo pageTitle="Skill Tests" />
      <div className="page-wrapper dashboard">
        <span className="header-span"></span>
        <DashboardHeader
          logo={"/images/human_capital_fav.png"}
          ac_holder={"Jobrator"}
        />
        <MobileMenu />
        <DashboardSidebar
          getIsSidebarOpen={getIsSidebarOpen}
          setIsSidebarOpen={setIsSidebarOpen}
        />
        <section className="user-dashboard">
          <div className="dashboard-outer">
            <BreadCrumb
              title="Skill Tests"
              getIsSidebarOpen={getIsSidebarOpen}
              setIsSidebarOpen={setIsSidebarOpen}
            />

            <div className="row">
              <div className="col-lg-12">
                <div className="ls-widget">
                  <div
                    className="widget-title"
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      flexWrap: "wrap",
                      gap: "12px",
                    }}
                  >
                    <h4 style={{ margin: 0 }}>Available Skill Tests</h4>

                    {/* Filter Section */}
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: "8px",
                        position: "relative",
                      }}
                    >
                      {/* Search Input */}
                      <div style={{ position: "relative" }}>
                        <input
                          type="text"
                          placeholder="Search exams..."
                          value={searchQuery}
                          onChange={(e) => setSearchQuery(e.target.value)}
                          style={{
                            padding: "8px 12px",
                            paddingRight: "36px",
                            border: "1px solid #e0e0e0",
                            borderRadius: "6px",
                            fontSize: "14px",
                            width: "220px",
                            outline: "none",
                            transition: "border-color 0.2s",
                          }}
                          onFocus={(e) => {
                            e.target.style.borderColor = "#1967d2";
                          }}
                          onBlur={(e) => {
                            e.target.style.borderColor = "#e0e0e0";
                          }}
                        />
                        {searchQuery && (
                          <button
                            onClick={() => setSearchQuery("")}
                            style={{
                              position: "absolute",
                              right: "8px",
                              top: "50%",
                              transform: "translateY(-50%)",
                              background: "none",
                              border: "none",
                              cursor: "pointer",
                              fontSize: "16px",
                              color: "#999",
                              padding: "4px",
                            }}
                          >
                            ×
                          </button>
                        )}
                      </div>
                    </div>
                  </div>
                  <div className="widget-content">
                    {loadingExams && <p>Loading tests...</p>}
                    {examsError && (
                      <div className="alert alert-danger">
                        <strong>Error:</strong> {examsError}
                        <br />
                        <button
                          onClick={() => window.location.reload()}
                          className="btn btn-sm btn-outline-danger mt-2"
                        >
                          Retry
                        </button>
                      </div>
                    )}

                    {!loadingExams && filteredExams.length === 0 && (
                      <p>
                        {searchQuery
                          ? `No tests found matching "${searchQuery}".`
                          : "No active tests available."}
                      </p>
                    )}

                    <div className="row gx-4 gy-3">
                      {filteredExams.map((exam) => {
                        const actualExamId = Number(exam.id);
                        const compositeKey = `${(exam.title || exam.name || "").toLowerCase()}_${(exam.role || "").toLowerCase()}`;

                        const cooldownInfo = getExamCooldownInfo(
                          actualExamId,
                          exam.title || exam.name || "",
                          exam.role || "",
                        );
                        const showCooldownMessage = cooldownInfo.isInCooldown;

                        const completedAttempt =
                          examAttempts.get(actualExamId) ||
                          (compositeKey !== "_"
                            ? examAttempts.get(compositeKey as any)
                            : undefined);
                        const completedScore =
                          completedAttempt?.percentage !== undefined &&
                          completedAttempt?.percentage !== null
                            ? Math.round(completedAttempt.percentage)
                            : null;

                        return (
                          <div className="col-md-6" key={exam.id}>
                            <div
                              className="h-100 d-flex flex-column"
                              style={{
                                position: "relative",
                                minHeight: "275px",
                                border: "1px solid #d8ecf1",
                                borderRadius: "10px",
                                padding: "20px 24px 18px",
                                backgroundColor: "#f4fbfd",
                                boxShadow: "0 2px 8px rgba(5, 88, 117, 0.08)",
                                transition: "all 0.3s ease",
                                cursor: showCooldownMessage
                                  ? "default"
                                  : "pointer",
                              }}
                              onMouseEnter={(e) => {
                                if (!showCooldownMessage) {
                                  e.currentTarget.style.boxShadow =
                                    "0 4px 16px rgba(0, 0, 0, 0.12)";
                                  e.currentTarget.style.transform =
                                    "translateY(-2px)";
                                }
                              }}
                              onMouseLeave={(e) => {
                                e.currentTarget.style.boxShadow =
                                  "0 2px 8px rgba(0, 0, 0, 0.08)";
                                e.currentTarget.style.transform =
                                  "translateY(0)";
                              }}
                            >
                              {completedScore !== null && (
                                <p
                                  style={{
                                    position: "absolute",
                                    top: "12px",
                                    left: "50%",
                                    transform: "translateX(-50%)",
                                    margin: 0,
                                    fontSize: "16px",
                                    color: "#138808",
                                    fontWeight: 700,
                                    textAlign: "center",
                                  }}
                                >
                                  You Scored {completedScore}%
                                </p>
                              )}
                              <h5
                                className="mb-2"
                                style={{
                                  fontSize: "26px",
                                  fontWeight: 700,
                                  lineHeight: 1.2,
                                  color: "#212245",
                                }}
                              >
                                {exam.title || exam.name}
                              </h5>
                              <p
                                className="mb-2"
                                style={{ fontSize: "14px", color: "#555555" }}
                              >
                                <strong>Duration:</strong>{" "}
                                {exam.duration ? `${exam.duration} min` : "-"}
                              </p>
                              {exam.description && (
                                <p
                                  className="mb-0"
                                  style={{
                                    fontSize: "14px",
                                    color: "#56606b",
                                    lineHeight: "1.6",
                                  }}
                                >
                                  <strong>Description:</strong>{" "}
                                  {exam.description.length > 120
                                    ? `${exam.description.slice(0, 120)}...`
                                    : exam.description}
                                </p>
                              )}

                              <div
                                className="mt-auto pt-3"
                                style={{ textAlign: "center" }}
                              >
                                {showCooldownMessage ? (
                                  <>
                                    <button
                                      className="theme-btn btn-style-three mb-2 disabled"
                                      disabled
                                      style={{
                                        display: "inline-block",
                                        minWidth: "175px",
                                        padding: "10px 16px",
                                        fontSize: "14px",
                                        borderRadius: "4px",
                                        opacity: "0.6",
                                        cursor: "not-allowed",
                                      }}
                                    >
                                      Already Taken
                                    </button>
                                    <p
                                      style={{
                                        margin: "12px 0 0 0",
                                        fontSize: "13px",
                                        color: "#0e0f0e",
                                        backgroundColor: "#fff9e6",
                                        padding: "10px 14px",
                                        borderRadius: "6px",
                                        border: "1px solid #ffe58f",
                                      }}
                                    >
                                      You have already taken this test. You can
                                      retake it after{" "}
                                      <strong>
                                        {formatDate(
                                          cooldownInfo.nextAvailableDate!,
                                        )}
                                      </strong>
                                      .
                                    </p>
                                  </>
                                ) : isEligible(exam) ? (
                                  <button
                                    onClick={() => handleStartTest(exam)}
                                    className="theme-btn btn-style-one"
                                    style={{
                                      display: "inline-block",
                                      minWidth: "175px",
                                      padding: "10px 16px",
                                      fontSize: "14px",
                                      borderRadius: "4px",
                                    }}
                                  >
                                    Take Test
                                  </button>
                                ) : (
                                  <button
                                    className="theme-btn btn-style-one disabled"
                                    disabled
                                    style={{
                                      display: "inline-block",
                                      minWidth: "175px",
                                      padding: "10px 16px",
                                      fontSize: "14px",
                                      borderRadius: "4px",
                                      opacity: "0.6",
                                      cursor: "not-allowed",
                                    }}
                                  >
                                    Not eligible
                                  </button>
                                )}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
        <CopyrightFooter />
      </div>
    </>
  );
};

export default SkillTestIndex;
