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 {
  usePsychometricApi,
  Test,
} from "../../../utils/hooks/usePsychometricApi";
import { useAuth } from "../../../contexts/auth";
import { useRouter } from "next/router";
import Link from "next/link";
import { useGetCandidateProfileDetails } from "../../../utils/hooks/useGetCandidateProfileDetails";

interface ExamAttempt {
  examId: number;
  endTime: string;
  startTime: string;
  status: string;
}

// Cooldown period in months for psychometric tests
const COOLDOWN_MONTHS = 6;

const Index = () => {
  const [getIsSidebarOpen, setIsSidebarOpen] = useState(false);
  const psychApi = usePsychometricApi();
  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<Test[]>([]);
  const [loadingExams, setLoadingExams] = useState(false);
  const [examsError, setExamsError] = useState<string | null>(null);
  const [examAttempts, setExamAttempts] = useState<Map<number, ExamAttempt>>(
    new Map(),
  );

  // 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 psychApi.getResults(candidateId);
        console.log(
          "Fetched psychometric exam results for cooldown check:",
          results,
        );

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

            // Track both COMPLETED and IN_PROGRESS exams for cooldown
            if (examId && (startTime || endTime)) {
              const existing = attemptsMap.get(examId);
              const attemptTime = startTime || endTime;
              // Keep the most recent attempt
              if (
                !existing ||
                new Date(attemptTime) >
                  new Date(existing.startTime || existing.endTime)
              ) {
                attemptsMap.set(examId, { examId, endTime, startTime, status });
              }
            }
          });
        }
        console.log("Psychometric exam attempts map:", attemptsMap);
        setExamAttempts(attemptsMap);
      } catch (err) {
        console.error("Failed to fetch psychometric exam attempts:", err);
      }
    };

    fetchExamAttempts();
  }, [candidateId]);

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

        // Handle various response formats
        let examsArray: Test[] = [];
        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.psychometricExams)) {
            examsArray = data.psychometricExams;
          }
        }

        setExams(examsArray || []);
      } 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();
  }, []);

  // Determine whether an exam should be considered active.
  const isExamActive = (exam: Test) => {
    const v = (exam as any).isActive;
    if (v === false) return false;
    if (v === 0) return false;
    if (v === "0") return false;
    return true;
  };

  const activeExams = exams.filter(isExamActive);

  const isEligible = (exam: Test) => {
    if (!userRole || String(userRole).toLowerCase() !== "candidate") {
      return false;
    }
    return true;
  };

  // Check if exam is in cooldown period (6 months)
  const getExamCooldownInfo = (examId: number) => {
    const attempt = examAttempts.get(examId);
    if (!attempt) {
      return { isInCooldown: false, nextAvailableDate: null };
    }

    // Use startTime for cooldown calculation (as per backend logic)
    const attemptTime = attempt.startTime || attempt.endTime;
    if (!attemptTime) {
      return { isInCooldown: false, nextAvailableDate: null };
    }

    const attemptDate = new Date(attemptTime);
    const nextAvailableDate = new Date(attemptDate);
    nextAvailableDate.setMonth(nextAvailableDate.getMonth() + COOLDOWN_MONTHS);

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

    return { isInCooldown, nextAvailableDate };
  };

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

  return (
    <>
      <Seo pageTitle="Psychometric Test" />
      <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="Psychometric Test"
              getIsSidebarOpen={getIsSidebarOpen}
              setIsSidebarOpen={setIsSidebarOpen}
            />

            <div className="row">
              <div className="col-lg-12">
                <div className="ls-widget">
                  <div className="widget-title">
                    <h4>Available Tests</h4>
                  </div>
                  <div className="widget-content">
                    {loadingExams && <p>Loading exams...</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 && activeExams.length === 0 && (
                      <p>No active tests available.</p>
                    )}

                    <div className="row gx-4 gy-3">
                      {activeExams.map((exam) => {
                        const cooldownInfo = getExamCooldownInfo(exam.id);
                        const showCooldownMessage = cooldownInfo.isInCooldown;
                        const attempt = examAttempts.get(exam.id);
                        const hasCompletedAttempt =
                          String(attempt?.status || "").toUpperCase() ===
                          "COMPLETED";

                        return (
                          <div className="col-md-6" key={exam.id}>
                            <div
                              className="h-100 d-flex flex-column"
                              style={{
                                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)";
                              }}
                            >
                              <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) ? (
                                  <Link
                                    href={`/dashboard/psychometic-test/startexam?examId=${exam.id}`}
                                    className="theme-btn btn-style-one"
                                    style={{
                                      display: "inline-block",
                                      minWidth: "175px",
                                      padding: "10px 16px",
                                      fontSize: "14px",
                                      borderRadius: "4px",
                                    }}
                                  >
                                    Continue to Test
                                  </Link>
                                ) : (
                                  <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>
                                )}

                                {hasCompletedAttempt && candidateId && (
                                  <div style={{ marginTop: "10px" }}>
                                    <Link
                                      href={`/candidate/${candidateId}`}
                                      className="theme-btn btn-style-three"
                                      style={{
                                        display: "inline-block",
                                        minWidth: "175px",
                                        padding: "10px 16px",
                                        fontSize: "14px",
                                        borderRadius: "4px",
                                      }}
                                    >
                                      View Result
                                    </Link>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
        <CopyrightFooter />
      </div>
    </>
  );
};

export default Index;
