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

type Exam = {
  id: number;
  title: string;
  description?: string;
  duration?: number;
  passingScore?: number;
  isActive?: boolean;
  companyId?: number | null;
  jobPostId?: number | null;
  skillQuestionLibrary?: {
    id: number;
    title: string;
  };
  jobPost?: {
    id: number;
    title: string;
    company?: {
      name: string;
    };
  };
  created_at?: string;
  updated_at?: string;
};

type Library = {
  id: number;
  name: string;
  title?: string;
  description?: string;
};

const ShowExams = () => {
  const skillApi = useSkillApi() as any;
  const [exams, setExams] = useState<Exam[]>([]);
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deleteConfirmId, setDeleteConfirmId] = useState<number | null>(null);
  const [selectedExam, setSelectedExam] = useState<Exam | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [currentCompanyId, setCurrentCompanyId] = useState<number | null>(null);

  // Edit modal states
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingExam, setEditingExam] = useState<Exam | null>(null);
  const [editTitle, setEditTitle] = useState("");
  const [editDescription, setEditDescription] = useState("");
  const [editDuration, setEditDuration] = useState(30);
  const [editSelectedLibraryId, setEditSelectedLibraryId] = useState<
    number | null
  >(null);
  const [editIsActive, setEditIsActive] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  const router = useRouter();
  const { isAuthenticated, loading: authLoading, userRole } = useAuth() as any;

  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.push("/login");
      return;
    }
    // Allow only Admin and Company roles to access skill test admin
    if (
      !authLoading &&
      isAuthenticated &&
      userRole &&
      !["Company"].includes(userRole)
    ) {
      router.push("/dashboard");
      return;
    }

    // Only fetch data if authenticated
    if (!authLoading && isAuthenticated) {
      // Fetch company profile to get current company ID
      const fetchCompanyProfile = async () => {
        try {
          const { resp } = (await useGetCompanyProfileDetails()) as any;
          setCurrentCompanyId(resp?.id || null);
        } catch (err) {
          console.error("Failed to fetch company profile:", err);
        }
      };

      // Load libraries first so we can map library names into exam objects
      const init = async () => {
        await fetchCompanyProfile();
        const libs = await fetchLibraries();
        await fetchExams(libs);
      };

      init();
    }
  }, [authLoading, isAuthenticated, userRole]);

  const fetchLibraries = async () => {
    try {
      const libs = await skillApi.getTestLibraries();
      const normalized = (libs || []).map((l: any) => ({
        id: l.id,
        name: l.name || l.title || "Untitled",
        title: l.title,
        description: l.description,
      }));
      setLibraries(normalized);
      return normalized;
    } catch (err) {
      console.error("Failed to fetch libraries", err);
      return [] as Library[];
    }
  };

  const fetchExams = async (libs?: Library[]) => {
    try {
      setLoading(true);
      setError(null);
      const data = await skillApi.getExams();

      // Handle various response formats
      let examsArray: Exam[] = [];
      if (Array.isArray(data)) {
        examsArray = data;
      } else if (data && typeof data === "object") {
        // Try to extract from nested structures
        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 exams: show only those created by admin (companyId = null) or current company
      const filteredExams = (examsArray || []).filter((exam: any) => {
        const examCompanyId = exam.companyId || exam.company_id || null;
        // Show if created by admin (no company ID) OR created by current company
        return examCompanyId === null || examCompanyId === currentCompanyId;
      });

      // Attach library object to each exam if possible
      const lookup = libs && libs.length ? libs : libraries;
      const mapped = (filteredExams || []).map((ex: any) => {
        const libId =
          ex.skillQuestionLibrary?.id ||
          ex.skillQuestionLibraryId ||
          ex.skill_question_library_id ||
          (ex.skillQuestionLibrary && (ex.skillQuestionLibrary as any).id);

        const lib = lookup ? lookup.find((l) => l.id === libId) : undefined;
        return {
          ...ex,
          skillQuestionLibrary: lib
            ? { id: lib.id, title: lib.title || lib.name }
            : ex.skillQuestionLibrary || null,
        };
      });

      // Fetch job details for exams with jobPostId
      const examsWithJobDetails = await Promise.all(
        mapped.map(async (exam: Exam) => {
          if (exam.jobPostId) {
            try {
              const { resp } = await useGetJobDetails(
                exam.jobPostId.toString(),
              );
              return {
                ...exam,
                jobPost: {
                  id: exam.jobPostId,
                  title: resp?.title || "Unknown Job",
                  company: resp?.company || null,
                },
              };
            } catch (jobErr) {
              console.error(
                `Failed to fetch job details for exam ${exam.id}:`,
                jobErr,
              );
              return {
                ...exam,
                jobPost: {
                  id: exam.jobPostId,
                  title: "Job details unavailable",
                  company: null,
                },
              };
            }
          }
          return exam;
        }),
      );

      setExams(examsWithJobDetails);
    } catch (err: any) {
      const errorMsg =
        err?.response?.data?.message || err?.message || "Failed to load exams";
      console.error("Failed to fetch skill test exams:", err);
      console.error("Error details:", {
        status: err?.response?.status,
        data: err?.response?.data,
        message: err?.message,
      });
      setError(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetails = (exam: Exam) => {
    setSelectedExam(exam);
    setShowModal(true);
  };

  const handleEdit = (exam: Exam) => {
    setEditingExam(exam);
    setEditTitle(exam.title);
    setEditDescription(exam.description || "");
    setEditDuration(exam.duration || 30);
    setEditIsActive(exam.isActive !== false);

    // Find the library ID from the exam data
    if (exam.skillQuestionLibrary) {
      setEditSelectedLibraryId(exam.skillQuestionLibrary.id);
    }

    setShowEditModal(true);
  };

  const handleSaveExam = async () => {
    if (!editingExam || !editTitle.trim()) {
      // alert("Please enter exam title");
      await Swal.fire({
        icon: "info",
        title: "Validation Error",
        text: "Please enter exam title",
      });
      return;
    }

    if (!editSelectedLibraryId) {
      // alert("Please select a question library");
      await Swal.fire({
        icon: "info",
        title: "Validation Error",
        text: "Please select a question library",
      });
      return;
    }

    try {
      setIsSaving(true);
      const payload = {
        skillQuestionLibraryId: editSelectedLibraryId,
        title: editTitle.trim(),
        description: editDescription || "",
        duration: editDuration || 30,
        isActive: editIsActive,
      };

      await skillApi.updateExam(editingExam.id, payload as any);
      // alert("Exam updated successfully!");
      await Swal.fire({
        icon: "success",
        title: "Success",
        text: "Exam updated successfully!",
      });
      setShowEditModal(false);
      fetchExams();
    } catch (err: any) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error("Update exam failed:", errorMessage, err);
      // alert("Failed to update exam: " + errorMessage);
      await Swal.fire({
        icon: "error",
        title: "Failed to update exam",
        text: errorMessage,
      });
    } finally {
      setIsSaving(false);
    }
  };

  const handleCloseEditModal = () => {
    setShowEditModal(false);
    setEditingExam(null);
    setEditTitle("");
    setEditDescription("");
    setEditDuration(30);
    setEditSelectedLibraryId(null);
    setEditIsActive(true);
  };

  const handleDelete = async (examId: number) => {
    if (
      !(
        await Swal.fire({
          title: "Are you sure?",
          text: "This action cannot be undone. The exam will be permanently deleted.",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Yes, delete it!",
        })
      ).isConfirmed
    ) {
      return;
    }

    try {
      setLoading(true);
      // Note: This assumes a deleteExam method exists in the API hook
      // If not available, you may need to add it to useSkillApi
      if (skillApi.deleteExam) {
        await skillApi.deleteExam(examId);
        // alert("Exam deleted successfully!");
        await Swal.fire({
          icon: "success",
          title: "Deleted!",
          text: "Exam deleted successfully!",
        });
        fetchExams();
      } else {
        // alert("Delete functionality not available yet.");
        await Swal.fire({
          icon: "info",
          title: "Not Implemented",
          text: "Delete functionality not available yet.",
        });
      }
    } catch (err: any) {
      const errorMsg = err?.response?.data?.message || "Failed to delete exam";
      console.error("Delete failed:", err);
      // alert(errorMsg);
      await Swal.fire({
        icon: "error",
        title: "Delete Failed",
        text: errorMsg,
      });
    } finally {
      setLoading(false);
      setDeleteConfirmId(null);
    }
  };

  const handleCreateNew = () => {
    router.push("/dashboard/skill-test/create-exam");
  };

  // Only show loading spinner during authentication check
  if (authLoading) {
    return (
      <>
        <Seo pageTitle="Skill Test Exams" />
        <div className="page-wrapper dashboard">
          <span className="header-span"></span>
          <DashboardHeader
            logo="/images/human_capital_fav.png"
            ac_holder="Jobrator"
          />
          <section className="user-dashboard">
            <div className="dashboard-outer">
              <BreadCrumb
                title="Skill Test Exams"
                getIsSidebarOpen={isSidebarOpen}
                setIsSidebarOpen={setIsSidebarOpen}
              />
              <div className="row">
                <div className="col-lg-12">
                  <div className="ls-widget">
                    <div className="tabs-box">
                      <div className="widget-content text-center py-5">
                        <div className="spinner-border mb-4" role="status">
                          <span className="visually-hidden">Loading...</span>
                        </div>
                        <p>Authenticating...</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
          <CopyrightFooter />
        </div>
      </>
    );
  }

  return (
    <>
      <Seo pageTitle="Skill Test Exams" />
      <div className="page-wrapper dashboard">
        <span className="header-span"></span>
        <DashboardHeader
          logo="/images/human_capital_fav.png"
          ac_holder="Jobrator"
        />
        <MobileMenu />
        <DashboardSidebar
          getIsSidebarOpen={isSidebarOpen}
          setIsSidebarOpen={setIsSidebarOpen}
        />
        <section className="user-dashboard">
          <div className="dashboard-outer">
            <BreadCrumb
              title="Skill Test Exams"
              getIsSidebarOpen={isSidebarOpen}
              setIsSidebarOpen={setIsSidebarOpen}
            />
            <div className="row">
              <div className="col-lg-12">
                <div className="ls-widget">
                  <div className="tabs-box">
                    <div className="widget-title">
                      <h4>Skill Test Exams</h4>
                      <button
                        className="theme-btn btn-style-one"
                        onClick={handleCreateNew}
                      >
                        + Create New Exam
                      </button>
                    </div>

                    {error && (
                      <div className="alert alert-danger mt-3">{error}</div>
                    )}

                    {/* Show loading state ONLY for exam data, not entire page */}
                    {loading ? (
                      <div className="widget-content text-center py-5">
                        <div className="spinner-border mb-4" role="status">
                          <span className="visually-hidden">Loading...</span>
                        </div>
                        <p>Loading exams...</p>
                      </div>
                    ) : exams.length === 0 ? (
                      <div className="widget-content text-center py-5">
                        <p className="text-muted">
                          No exams found. Create your first exam to get started!
                        </p>
                      </div>
                    ) : (
                      <div className="widget-content">
                        <div className="row">
                          {exams.map((exam) => (
                            <div
                              key={exam.id}
                              className="col-lg-4 col-md-6 mb-4"
                            >
                              <div
                                className="job-card border rounded p-4 h-100"
                                style={{
                                  boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
                                  transition: "transform 0.3s, box-shadow 0.3s",
                                }}
                                onMouseEnter={(e) => {
                                  e.currentTarget.style.transform =
                                    "translateY(-5px)";
                                  e.currentTarget.style.boxShadow =
                                    "0 4px 12px rgba(0,0,0,0.15)";
                                }}
                                onMouseLeave={(e) => {
                                  e.currentTarget.style.transform =
                                    "translateY(0)";
                                  e.currentTarget.style.boxShadow =
                                    "0 2px 8px rgba(0,0,0,0.1)";
                                }}
                              >
                                <div className="d-flex justify-content-between align-items-start mb-3">
                                  <div>
                                    <h5 className="mb-1 fw-bold text-dark">
                                      {exam.title}
                                    </h5>
                                    <p className="text-muted small mb-0">
                                      ID: {exam.id}
                                    </p>
                                  </div>
                                  <div className="d-flex flex-column gap-1 align-items-end">
                                    <span
                                      className={`badge ${exam.isActive ? "bg-success" : "bg-secondary"}`}
                                    >
                                      {exam.isActive ? "Active" : "Inactive"}
                                    </span>
                                  </div>
                                </div>

                                <div className="exam-details mb-3">
                                  <div className="detail-row mb-2">
                                    <strong className="text-muted small">
                                      Duration:
                                    </strong>
                                    <p className="mb-0">
                                      {exam.duration
                                        ? `${exam.duration} min`
                                        : "-"}
                                    </p>
                                  </div>
                                  <div className="detail-row mb-2">
                                    <strong className="text-muted small">
                                      Library:
                                    </strong>
                                    <p className="mb-0">
                                      {exam.skillQuestionLibrary?.title || "-"}
                                    </p>
                                  </div>
                                  {exam.jobPost && (
                                    <div className="detail-row mb-2">
                                      <strong className="text-muted small">
                                        Job Post:
                                      </strong>
                                      <p className="mb-0 d-flex align-items-center gap-2">
                                        <span
                                          className="text-muted small"
                                          style={{ fontSize: "14px" }}
                                        >
                                          {exam.jobPost.title}
                                        </span>
                                        <button
                                          className="btn btn-sm btn-outline-primary p-1"
                                          onClick={() =>
                                            router.push(
                                              `/dashboard/manage-jobs/${exam.jobPost?.id}`,
                                            )
                                          }
                                          title="View Job Details"
                                          style={{
                                            border: "none",
                                            background: "transparent",
                                            padding: "6px 12px",
                                            fontSize: "22px",
                                          }}
                                        >
                                          <span className="la la-eye text-primary"></span>
                                        </button>
                                      </p>
                                    </div>
                                  )}
                                  {exam.description && (
                                    <div className="detail-row mb-2">
                                      <strong className="text-muted small">
                                        Description:
                                      </strong>
                                      <p className="mb-0 small text-muted">
                                        {exam.description.substring(0, 80)}
                                        {exam.description.length > 80
                                          ? "..."
                                          : ""}
                                      </p>
                                    </div>
                                  )}
                                </div>

                                <div className="d-flex gap-2 mt-4">
                                  <button
                                    className="theme-btn btn-style-one flex-grow-1"
                                    onClick={() => handleViewDetails(exam)}
                                    style={{
                                      padding: "10px 20px",
                                      fontSize: "14px",
                                    }}
                                  >
                                    View
                                  </button>
                                  <button
                                    className="btn btn-sm btn-warning flex-grow-1"
                                    onClick={() => handleEdit(exam)}
                                    style={{
                                      padding: "10px 20px",
                                      fontSize: "14px",
                                    }}
                                  >
                                    Edit
                                  </button>
                                  <button
                                    className="btn btn-sm btn-danger flex-grow-1"
                                    onClick={() => handleDelete(exam.id)}
                                    style={{
                                      padding: "10px 20px",
                                      fontSize: "14px",
                                    }}
                                  >
                                    Delete
                                  </button>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
        <CopyrightFooter />
      </div>

      {/* Details Modal */}
      {showModal && selectedExam && (
        <div
          className="modal d-block"
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <div className="modal-dialog modal-lg">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">Exam Details</h5>
                <button
                  type="button"
                  className="btn-close"
                  onClick={() => setShowModal(false)}
                ></button>
              </div>
              <div className="modal-body">
                <div className="row mb-3">
                  <div className="col-md-6">
                    <strong>Title:</strong>
                    <p>{selectedExam.title}</p>
                  </div>
                  <div className="col-md-6">
                    <strong>ID:</strong>
                    <p>{selectedExam.id}</p>
                  </div>
                </div>
                <div className="row mb-3">
                  <div className="col-12">
                    <strong>Description:</strong>
                    <p>{selectedExam.description || "-"}</p>
                  </div>
                </div>
                <div className="row mb-3">
                  <div className="col-md-6">
                    <strong>Duration:</strong>
                    <p>
                      {selectedExam.duration
                        ? `${selectedExam.duration} minutes`
                        : "-"}
                    </p>
                  </div>
                </div>
                <div className="row mb-3">
                  <div className="col-md-6">
                    <strong>Question Library:</strong>
                    <p>{selectedExam.skillQuestionLibrary?.title || "-"}</p>
                  </div>
                  <div className="col-md-6">
                    <strong>Status:</strong>
                    <p>
                      {selectedExam.isActive ? (
                        <span className="badge bg-success">Active</span>
                      ) : (
                        <span className="badge bg-secondary">Inactive</span>
                      )}
                    </p>
                  </div>
                </div>
                {selectedExam.jobPost && (
                  <div className="row mb-3">
                    <div className="col-12">
                      <strong>Associated Job Post:</strong>
                      <p className="d-flex align-items-center gap-2">
                        <span className="text fw-medium">
                          {selectedExam.jobPost.title}
                        </span>
                        <button
                          className="btn btn-sm btn-outline-primary"
                          onClick={() =>
                            router.push(
                              `/dashboard/manage-jobs/${selectedExam.jobPost?.id}`,
                            )
                          }
                          title="View Job Details"
                          style={{
                            border: "none",
                            background: "transparent",
                            padding: "6px 12px",
                            fontSize: "16px",
                          }}
                        >
                          <span className="la la-eye text-primary"></span>
                        </button>
                        {selectedExam.jobPost.company && (
                          <small className="text-muted">
                            ({selectedExam.jobPost.company.name})
                          </small>
                        )}
                      </p>
                    </div>
                  </div>
                )}
                {/* Created/Updated intentionally removed from details view */}
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => setShowModal(false)}
                >
                  Close
                </button>
                <button
                  type="button"
                  className="btn btn-warning"
                  onClick={() => {
                    setShowModal(false);
                    handleEdit(selectedExam);
                  }}
                >
                  Edit
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Edit Exam Modal */}
      {showEditModal && editingExam && (
        <div
          className="modal d-block"
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <div className="modal-dialog modal-lg">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">Edit Exam</h5>
                <button
                  type="button"
                  className="btn-close"
                  onClick={handleCloseEditModal}
                  disabled={isSaving}
                ></button>
              </div>
              <div className="modal-body">
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    handleSaveExam();
                  }}
                >
                  <div className="mb-3">
                    <label className="form-label">Exam Title</label>
                    <input
                      type="text"
                      className="form-control"
                      value={editTitle}
                      onChange={(e) => setEditTitle(e.target.value)}
                      disabled={isSaving}
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Description</label>
                    <textarea
                      className="form-control"
                      rows={3}
                      value={editDescription}
                      onChange={(e) => setEditDescription(e.target.value)}
                      disabled={isSaving}
                    />
                  </div>

                  <div className="row mb-3">
                    <div className="col-md-6">
                      <label className="form-label">Duration (minutes)</label>
                      <input
                        type="number"
                        className="form-control"
                        value={editDuration}
                        onChange={(e) =>
                          setEditDuration(parseInt(e.target.value) || 30)
                        }
                        disabled={isSaving}
                      />
                    </div>
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Question Library</label>
                    <select
                      className="form-select"
                      value={editSelectedLibraryId || ""}
                      onChange={(e) =>
                        setEditSelectedLibraryId(
                          parseInt(e.target.value) || null,
                        )
                      }
                      disabled={isSaving}
                    >
                      <option value="">Select a library</option>
                      {libraries.map((lib) => (
                        <option key={lib.id} value={lib.id}>
                          {lib.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="mb-3 form-check">
                    <input
                      type="checkbox"
                      className="form-check-input"
                      id="editIsActive"
                      checked={editIsActive}
                      onChange={(e) => setEditIsActive(e.target.checked)}
                      disabled={isSaving}
                    />
                    <label className="form-check-label" htmlFor="editIsActive">
                      Active
                    </label>
                  </div>
                </form>
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-danger"
                  onClick={handleCloseEditModal}
                  disabled={isSaving}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="theme-btn btn-style-one"
                  style={{
                    display: "inline-block",
                    padding: "10px 20px",
                    fontSize: "14px",
                    borderRadius: "4px",
                  }}
                  onClick={handleSaveExam}
                  disabled={isSaving}
                >
                  {isSaving ? "Saving..." : "Save Changes"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default ShowExams;
