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 Swal from "sweetalert2";

type Library = {
  id: number;
  name: string;
  title?: string;
  description?: string;
  questionCount?: number;
  creator?: {
    id: number;
    name?: string;
    username?: string;
    email?: string;
    createdAt: string;
    candidate?: {
      firstName?: string;
      lastName?: string;
    };
    company?: {
      name?: string;
    };
  };
  createdBy?: number;
};

const CreateExams = () => {
  const skillApi = useSkillApi() as any;
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [duration, setDuration] = useState(30);
  const [selectedLibraryId, setSelectedLibraryId] = useState<number | null>(
    null,
  );
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const { isAuthenticated, loading: authLoading, userRole } = useAuth() as any;
  const [currentCompanyId, setCurrentCompanyId] = useState<number | null>(null);

  // State for viewing library questions in modal
  const [viewingLibraryId, setViewingLibraryId] = useState<number | null>(null);
  const [viewingLibraryQuestions, setViewingLibraryQuestions] = useState<any[]>(
    [],
  );
  const [viewingLibraryName, setViewingLibraryName] = useState("");
  const [loadingViewQuestions, setLoadingViewQuestions] = useState(false);

  // State for editing/adding a question
  const [editingQuestionId, setEditingQuestionId] = useState<number | null>(
    null,
  );
  const [editingQuestion, setEditingQuestion] = useState<any>(null);
  const [editTitle, setEditTitle] = useState("");
  const [editTopic, setEditTopic] = useState("");
  const [editScore, setEditScore] = useState(1);
  const [editOptions, setEditOptions] = useState<{ [key: string]: string }>({});
  const [editWeights, setEditWeights] = useState<{ [key: string]: number }>({});
  const [editAnswer, setEditAnswer] = useState<string>("");
  const [savingQuestion, setSavingQuestion] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isAddingQuestion, setIsAddingQuestion] = useState(false);

  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.push("/login");
      return;
    }
    // Allow only Company roles to access skill test
    if (
      !authLoading &&
      isAuthenticated &&
      userRole &&
      !["Company"].includes(userRole)
    ) {
      router.push("/dashboard");
      return;
    }
    // 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);
      }
    };

    fetchCompanyProfile();
    fetchLibraries();
  }, [authLoading, isAuthenticated]);

  const fetchLibraries = async () => {
    try {
      setLoading(true);
      const libs = await skillApi.getTestLibraries();

      // Map through and fetch question counts for each library
      const normalized = await Promise.all(
        (libs || []).map(async (l: any) => {
          let questionCount = 0;

          // Always fetch questions to get accurate count
          try {
            const questions = await skillApi.getQuestions(l.id);
            questionCount = Array.isArray(questions) ? questions.length : 0;
          } catch (err) {
            console.debug(
              `Could not fetch questions for library ${l.id}:`,
              err,
            );
            // Fallback to library's noOfQuestions if API fails
            questionCount =
              l.noOfQuestions || l.no_of_questions || l.questionCount || 0;
          }

          return {
            id: l.id,
            name: l.title || l.name || "Untitled",
            title: l.title || l.name,
            description: l.description,
            questionCount: questionCount,
            creator: l.creator || null,
            createdBy: l.createdBy || l.created_by || null,
          };
        }),
      );
      setLibraries(normalized);
    } catch (err) {
      console.error("Failed to fetch libraries", err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateExam = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedLibraryId) {
      const resp = await Swal.fire({
        title: "No Library Selected",
        text: "Please select a question library to create an exam.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Select Library",
        cancelButtonText: "Cancel",
      });
      if (resp.isConfirmed) {
        return;
      }
    }

    if (!title.trim()) {
      await Swal.fire({
        icon: "error",
        text: "Please enter exam title",
      });
      return;
    }

    try {
      setLoading(true);

      // Get the selected library to get question count
      const selectedLib = libraries.find((lib) => lib.id === selectedLibraryId);
      const questionCount = selectedLib?.questionCount || 0;

      const payload = {
        skillQuestionLibraryId: selectedLibraryId,
        title: title,
        description: description || "",
        duration: duration || 30,
        questionCount: questionCount,
        isActive: true,
      };

      await skillApi.createExam(payload);

      await Swal.fire({
        icon: "success",
        text: "Skill exam created successfully!",
      });

      setTitle("");
      setDescription("");
      setDuration(30);
      setSelectedLibraryId(null);
      fetchLibraries();

      if (sessionStorage.getItem("postExamCreationRedirect")) {
        router.push(sessionStorage.getItem("postExamCreationRedirect")!);
      }
    } catch (err: any) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error("Create exam failed:", errorMessage, err);
      await Swal.fire({
        icon: "error",
        title: "Create Exam Failed",
        text: errorMessage,
      });
    } finally {
      setLoading(false);
    }
  };

  // Function to view questions for a specific library in modal
  const handleViewLibraryQuestions = async (
    libraryId: number,
    libraryName: string,
  ) => {
    try {
      setLoadingViewQuestions(true);
      setViewingLibraryId(libraryId);
      setViewingLibraryName(libraryName);

      // Get questions for this library
      const questions = await skillApi.getLibraryQuestions(libraryId);
      setViewingLibraryQuestions(questions || []);
    } catch (err) {
      console.error("Failed to fetch library questions", err);
      setViewingLibraryQuestions([]);
      await Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to load questions for this library",
      });
    } finally {
      setLoadingViewQuestions(false);
    }
  };

  const getCreatorName = (library: Library): string => {
    if (!library.creator) {
      return "Unknown";
    }

    const { name, username, email, candidate, company } = library.creator;

    // If user has a candidate profile, use candidate name
    if (candidate && (candidate.firstName || candidate.lastName)) {
      const firstName = candidate.firstName || "";
      const lastName = candidate.lastName || "";
      return `${firstName} ${lastName}`.trim();
    }

    // If user has a company profile, use company name
    if (company && company.name) {
      return company.name;
    }

    // Otherwise use user's name, username, or email
    if (name) {
      return name;
    } else if (username) {
      return username;
    } else if (email) {
      return email;
    }

    return "Unknown";
  };

  const getLibraryUpdationDate = (library: Library): string => {
    console.log("library>>>", library.creator);
    if (library.creator && library.creator.createdAt) {
      return library.creator.createdAt.split("T")[0];
    }
    return "";
  };

  const handleQuestionSetReplication = async (libraryId: number) => {
    const resp = await Swal.fire({
      title: "Replicate Question Library",
      text: "Are you sure you want to replicate this question library?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Replicate",
      cancelButtonText: "Cancel",
    });
    if (!resp.isConfirmed) {
      return;
    }
    try {
      setLoading(true);
      // Step 1: Fetch original library
      const originalLibrary = libraries.find((l) => l.id === libraryId);
      if (!originalLibrary) {
        throw new Error("Library not found");
      }

      // Step 2: Fetch all questions from the library
      const questions = await skillApi.getLibraryQuestions(libraryId);

      if (!questions || questions.length === 0) {
        await Swal.fire({
          icon: "warning",
          title: "No Questions Found",
          text: "This library has no questions to replicate.",
        });
        return;
      }

      // Step 3: Create new library
      const newLibraryPayload = {
        title: `${originalLibrary.name} (Copy)`,
        description: originalLibrary.description || "",
        subject: originalLibrary.name,
        role: originalLibrary.name,
        noOfQuestions: questions.length,
      };

      const newLibrary = await skillApi.createLibrary(newLibraryPayload);
      const newLibraryId = newLibrary.id;

      // Step 4: Copy each question
      for (const q of questions) {
        const payload = {
          skillQuestionLibraryId: newLibraryId,
          questionText: q.questionText,
          topic: q.topic,
          options: q.options,
          weights: q.weights,
          answer: q.answer || q.correctAnswer,
        };

        await skillApi.createQuestion(payload);
      }

      setLoading(false);

      await Swal.fire({
        icon: "success",
        title: "Library Replicated",
        text: "A new editable copy of this question set has been created.",
      });

      // Refresh libraries list
      await fetchLibraries();
    } catch (error) {
      console.error("Replication failed:", error);
      await Swal.fire({
        icon: "error",
        title: "Replication Failed",
        text: "Unable to replicate the question library.",
      });
    }
  };

  const handleCreateNewLibrary = () => {
    sessionStorage.setItem("redirectTo", "create-exam");
    router.push("/dashboard/skill-test/create-questionset");
  };

  const handleDeleteQuestion = async (questionId: number) => {
    const resp = await Swal.fire({
      title: "Delete Question",
      text: "Are you sure you want to delete this question?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, delete it!",
    });
    if (!resp.isConfirmed) {
      return;
    }

    try {
      await skillApi.deleteQuestion(questionId);
      // Refresh both the libraries list (to update question count) and the questions view
      await fetchLibraries();
      if (viewingLibraryId) {
        handleViewLibraryQuestions(viewingLibraryId, viewingLibraryName);
      }
    } catch (err: any) {
      console.error("Failed to delete question:", err);
      await Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to delete question",
      });
    }
  };

  const handleDeleteLibrary = async (libraryId: number) => {
    if (
      !(
        await Swal.fire({
          title: "Delete Library",
          text: "Are you sure you want to delete this library and all its questions?",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Yes, delete it!",
        })
      ).isConfirmed
    ) {
      return;
    }

    try {
      await skillApi.deleteLibrary(libraryId);
      setViewingLibraryId(null);
      setViewingLibraryQuestions([]);
      setViewingLibraryName("");
      fetchLibraries();
      if (selectedLibraryId === libraryId) {
        setSelectedLibraryId(null);
      }
    } catch (err: any) {
      console.error("Failed to delete library:", err);
      await Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to delete library",
      });
    }
  };

  // Function to close the viewing modal
  const handleCloseViewQuestions = () => {
    setViewingLibraryId(null);
    setViewingLibraryQuestions([]);
    setViewingLibraryName("");
  };

  // Function to open edit modal for a question
  const handleEditQuestion = (question: any) => {
    setEditingQuestionId(question.id);
    setEditingQuestion(question);
    setEditTitle(question.questionText || "");
    setEditTopic(question.topic || "");
    setEditOptions(question.options || { A: "", B: "", C: "", D: "" });
    setEditWeights(question.weights || { A: 0, B: 0, C: 0, D: 0 });
    setEditAnswer(question.correctAnswer || question.answer || "");
  };

  // Function to close edit modal
  const handleCloseEditQuestion = () => {
    setEditingQuestionId(null);
    setEditingQuestion(null);
    setEditTitle("");
    setEditTopic("");
    setEditOptions({});
    setEditWeights({});
    setEditAnswer("");
    setIsAddingQuestion(false);
  };

  // Open add-question modal
  const handleOpenAddQuestion = () => {
    setIsAddingQuestion(true);
    setEditingQuestionId(null);
    setEditingQuestion(null);
    setEditTitle("");
    setEditTopic("");
    setEditOptions({ A: "", B: "" });
    setEditWeights({ A: 0, B: 0 });
    setEditAnswer("");
  };

  // Function to add a new option
  const handleAddOption = () => {
    const currentKeys = Object.keys(editOptions);
    let nextKey = "E";

    for (let i = 0; i < 26; i++) {
      const letter = String.fromCharCode(65 + i);
      if (!currentKeys.includes(letter)) {
        nextKey = letter;
        break;
      }
    }

    setEditOptions({ ...editOptions, [nextKey]: "" });
    setEditWeights({ ...editWeights, [nextKey]: 0 });
  };

  // Function to remove an option
  const handleRemoveOption = (optionKey: string) => {
    const newOptions = { ...editOptions };
    const newWeights = { ...editWeights };
    delete newOptions[optionKey];
    delete newWeights[optionKey];

    if (editAnswer === optionKey) {
      setEditAnswer("");
    }

    setEditOptions(newOptions);
    setEditWeights(newWeights);
  };

  // Function to save edited/added question
  const handleSaveEditedQuestion = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editTitle.trim()) {
      await Swal.fire({
        icon: "error",
        title: "Error",
        text: "Question title is required",
      });
      return;
    }
    if (!editAnswer) {
      await Swal.fire({
        icon: "error",
        title: "Error",
        text: "Correct answer is required",
      });
      return;
    }

    try {
      setSavingQuestion(true);
      const payload = {
        skillQuestionLibraryId: viewingLibraryId,
        questionText: editTitle,
        topic: editTopic,
        options: editOptions,
        weights: editWeights,
        answer: editAnswer,
      };

      if (isAddingQuestion) {
        await skillApi.createQuestion(payload);
        await Swal.fire({
          icon: "success",
          title: "Success",
          text: "Question created successfully!",
        });
      } else {
        await skillApi.updateQuestion(editingQuestionId!, payload);
        await Swal.fire({
          icon: "success",
          title: "Success",
          text: "Question updated successfully!",
        });
      }
      handleCloseEditQuestion();
      // Refresh both the libraries list (to update question count) and the questions view
      await fetchLibraries();
      if (viewingLibraryId) {
        handleViewLibraryQuestions(viewingLibraryId, viewingLibraryName);
      }
    } catch (err: any) {
      console.error("Failed to save question:", err);
      await Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to save question",
      });
    } finally {
      setSavingQuestion(false);
    }
  };

  return (
    <>
      <Seo pageTitle="Create Skill Exam" />
      <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 container">
            <BreadCrumb
              title="Create Skill Exam"
              getIsSidebarOpen={isSidebarOpen}
              setIsSidebarOpen={setIsSidebarOpen}
            />

            <div className="row">
              {/* Left Column: Create Exam */}
              <div className="col-lg-4">
                <div className="ls-widget p-4">
                  <h5>Create New Exam</h5>

                  <div className="mb-3">
                    <label className="form-label">Exam Title *</label>
                    <input
                      type="text"
                      value={title}
                      onChange={(e) => setTitle(e.target.value)}
                      placeholder="e.g., JavaScript Skill Test"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Description</label>
                    <textarea
                      value={description}
                      onChange={(e) => setDescription(e.target.value)}
                      placeholder="Description (optional)"
                      rows={3}
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Duration (minutes) *</label>
                    <input
                      type="number"
                      value={duration}
                      onChange={(e) =>
                        setDuration(parseInt(e.target.value) || 30)
                      }
                      placeholder="Duration in minutes"
                      min={1}
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Select Library *</label>
                    <select
                      value={selectedLibraryId || ""}
                      onChange={(e) =>
                        setSelectedLibraryId(
                          e.target.value ? Number(e.target.value) : null,
                        )
                      }
                      className="form-control"
                    >
                      <option value="">-- Select a library --</option>
                      {libraries
                        .filter((lib) => lib.creator?.name !== "Jobrator Admin")
                        .map((lib) => (
                          <option key={lib.id} value={lib.id}>
                            {lib.name || lib.title} ({lib.questionCount || 0}{" "}
                            questions)
                          </option>
                        ))}
                    </select>
                  </div>

                  <button
                    className="theme-btn btn-style-one w-100"
                    onClick={handleCreateExam}
                    disabled={loading || !selectedLibraryId || !title.trim()}
                  >
                    {loading ? "Creating..." : "Create Exam"}
                  </button>
                </div>
              </div>

              {/* Right Column: Question Libraries */}
              <div className="col-lg-8">
                <div className="ls-widget p-4">
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      marginBottom: "20px",
                    }}
                  >
                    <h5 style={{ margin: 0 }}>
                      Question Libraries ({libraries.length})
                    </h5>
                    <button
                      className="theme-btn btn-style-one"
                      style={{
                        display: "inline-block",
                        padding: "10px 20px",
                        fontSize: "14px",
                        borderRadius: "4px",
                      }}
                      onClick={handleCreateNewLibrary}
                    >
                      + Create New Library
                    </button>
                  </div>

                  {loading ? (
                    <p>Loading...</p>
                  ) : libraries.length === 0 ? (
                    <p className="text-muted">No libraries available</p>
                  ) : (
                    <div style={{ maxHeight: "600px", overflowY: "auto" }}>
                      {libraries.map((lib) => (
                        <div
                          key={lib.id}
                          style={{
                            marginBottom: "15px",
                            padding: "12px",
                            border: "1px solid #dee2e6",
                            borderRadius: "4px",
                            backgroundColor: "#f8f9fa",
                          }}
                        >
                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-between",
                              alignItems: "stretch",
                              gap: "70px",
                            }}
                          >
                            {/* LEFT CONTENT */}
                            <div
                              style={{
                                flex: "1 1 auto",
                                minWidth: 0,
                              }}
                            >
                              <h6 style={{ margin: "0 0 5px 0" }}>
                                {lib.name || lib.title}
                              </h6>

                              <div
                                style={{
                                  display: "flex",
                                  gap: "15px",
                                  marginBottom: "5px",
                                }}
                              >
                                <small className="text-muted">
                                  {lib.questionCount || 0} questions
                                </small>
                              </div>

                              {lib.description && (
                                <p
                                  style={{
                                    margin: "5px 0 0 0",
                                    fontSize: "12px",
                                    color: "#666",
                                    overflowWrap: "break-word",
                                    wordBreak: "break-word",
                                    maxWidth: "100%",
                                  }}
                                >
                                  {lib.description}
                                </p>
                              )}
                            </div>

                            {/* RIGHT SIDE */}
                            <div
                              style={{
                                display: "flex",
                                flexDirection: "column",
                                justifyContent: "space-between",
                                alignItems: "flex-end",
                                flexShrink: 0,
                                minWidth: "120px",
                              }}
                            >
                              <div style={{ display: "flex", gap: "6px" }}>
                                <button
                                  className="theme-btn btn-style-one"
                                  style={{
                                    padding: "4px 8px",
                                    fontSize: "12px",
                                  }}
                                  onClick={() =>
                                    handleViewLibraryQuestions(
                                      lib.id,
                                      lib.name || lib.title || "",
                                    )
                                  }
                                >
                                  View
                                </button>

                                {lib.creator?.name !== "Jobrator Admin" && (
                                  <button
                                    className="btn btn-sm btn-danger"
                                    style={{ padding: "4px 8px" }}
                                    onClick={() => handleDeleteLibrary(lib.id)}
                                  >
                                    Delete
                                  </button>
                                )}
                              </div>

                              <small
                                className="text-muted"
                                style={{ marginTop: "auto" }}
                              >
                                Created by:{" "}
                                <strong>{getCreatorName(lib)}</strong>
                              </small>

                              <small className="text-muted">
                                Date: {getLibraryUpdationDate(lib)}
                              </small>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </section>
        <CopyrightFooter />
      </div>

      {/* Modal for viewing library questions */}
      {viewingLibraryId && (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0,0,0,0.5)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 1050,
          }}
          onClick={handleCloseViewQuestions}
        >
          <div
            style={{
              backgroundColor: "white",
              borderRadius: "8px",
              maxWidth: "900px",
              width: "90%",
              maxHeight: "90vh",
              display: "flex",
              flexDirection: "column",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: "20px",
                borderBottom: "1px solid #dee2e6",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <h5 style={{ margin: 0 }}>Questions in: {viewingLibraryName}</h5>
              <div
                style={{ display: "flex", gap: "10px", alignItems: "center" }}
              >
                {libraries.find((lib) => lib.id === viewingLibraryId)?.creator
                  ?.name !== "Jobrator Admin" ? (
                  <>
                    <button
                      className="theme-btn btn-style-one"
                      style={{
                        display: "inline-block",
                        padding: "5px 10px",
                        fontSize: "14px",
                        borderRadius: "4px",
                      }}
                      onClick={() => handleOpenAddQuestion()}
                    >
                      + Add Question
                    </button>

                    <button
                      className="btn btn-sm btn-danger"
                      onClick={() => handleDeleteLibrary(viewingLibraryId!)}
                    >
                      Delete Library
                    </button>
                  </>
                ) : (
                  <button
                    className="theme-btn btn-style-one"
                    style={{
                      display: "inline-block",
                      padding: "10px 12px",
                      fontSize: "16px",
                      borderRadius: "4px",
                    }}
                    onClick={() =>
                      handleQuestionSetReplication(viewingLibraryId!)
                    }
                  >
                    {loading ? "Replicating..." : "Replicate Library"}
                  </button>
                )}

                <button
                  type="button"
                  className="btn-close"
                  onClick={handleCloseViewQuestions}
                  aria-label="Close"
                ></button>
              </div>
            </div>
            <div style={{ padding: "20px", overflowY: "auto", flex: 1 }}>
              {loadingViewQuestions ? (
                <div style={{ textAlign: "center", padding: "40px 0" }}>
                  <div className="spinner-border text-primary" role="status">
                    <span className="visually-hidden">Loading...</span>
                  </div>
                  <p style={{ marginTop: "10px" }}>Loading questions...</p>
                </div>
              ) : viewingLibraryQuestions.length === 0 ? (
                <div style={{ textAlign: "center", padding: "40px 0" }}>
                  <p style={{ color: "#6c757d" }}>
                    No questions found in this library.
                  </p>
                </div>
              ) : (
                // Replace the question rendering section in your modal (around line 850-950)
                // This is the section inside: {viewingLibraryQuestions.map((q: any, idx: number) => (

                <div>
                  {viewingLibraryQuestions.map((q: any, idx: number) => {
                    // Check if this is an admin-created library
                    const isAdminLibrary =
                      libraries.find((lib) => lib.id === viewingLibraryId)
                        ?.creator?.name === "Jobrator Admin";

                    return (
                      <div
                        key={q.id}
                        style={{
                          marginBottom: "20px",
                          padding: "15px",
                          border: "1px solid #dee2e6",
                          borderRadius: "8px",
                          backgroundColor: "#f8f9fa",
                        }}
                      >
                        <div
                          style={{
                            display: "flex",
                            justifyContent: "space-between",
                            alignItems: "flex-start",
                            marginBottom: "10px",
                          }}
                        >
                          <h6 style={{ marginBottom: "5px" }}>
                            <span
                              className="badge bg-primary"
                              style={{ marginRight: "10px" }}
                            >
                              {idx + 1}
                            </span>
                            {q.questionText || q.title}
                          </h6>

                          {/* Only show edit/delete buttons if NOT admin library */}
                          {!isAdminLibrary && (
                            <div
                              style={{
                                display: "flex",
                                gap: "5px",
                                marginLeft: "10px",
                              }}
                            >
                              <button
                                className="btn btn-sm btn-warning"
                                onClick={() => handleEditQuestion(q)}
                                style={{
                                  padding: "4px 8px",
                                  fontSize: "12px",
                                }}
                              >
                                Edit
                              </button>
                              <button
                                className="btn btn-sm btn-danger"
                                onClick={() => handleDeleteQuestion(q.id)}
                                style={{
                                  padding: "4px 8px",
                                  fontSize: "12px",
                                }}
                              >
                                Delete
                              </button>
                            </div>
                          )}
                        </div>

                        {q.description && (
                          <p
                            style={{
                              fontSize: "14px",
                              color: "#6c757d",
                              marginBottom: "15px",
                            }}
                          >
                            {q.description}
                          </p>
                        )}
                        {q.score && (
                          <p
                            style={{
                              fontSize: "12px",
                              color: "#666",
                              marginBottom: "10px",
                            }}
                          >
                            <strong>Score:</strong> {q.score}
                          </p>
                        )}
                        {q.topic && (
                          <p
                            style={{
                              fontSize: "12px",
                              color: "#666",
                              marginBottom: "10px",
                            }}
                          >
                            <strong>Topic:</strong> {q.topic}
                          </p>
                        )}
                        <div>
                          {q.options &&
                            Object.entries(q.options).map(
                              ([key, value]: [string, any]) => {
                                const correctKey = q.answer || q.correctAnswer;
                                const isCorrect = correctKey === key;
                                return (
                                  <div
                                    key={key}
                                    style={{
                                      display: "flex",
                                      alignItems: "center",
                                      marginBottom: "10px",
                                      padding: "10px",
                                      borderRadius: "4px",
                                      backgroundColor: isCorrect
                                        ? "rgba(25, 135, 84, 0.1)"
                                        : "#fff",
                                      border: isCorrect
                                        ? "1px solid #198754"
                                        : "1px solid #dee2e6",
                                    }}
                                  >
                                    <span
                                      className={`badge ${isCorrect ? "bg-success" : "bg-secondary"}`}
                                      style={{
                                        minWidth: "30px",
                                        marginRight: "10px",
                                      }}
                                    >
                                      {key}
                                    </span>
                                    <span style={{ flex: 1 }}>{value}</span>
                                  </div>
                                );
                              },
                            )}
                        </div>
                        {(q.correctAnswer || q.answer) && (
                          <div style={{ marginTop: "10px" }}>
                            <small style={{ color: "#198754" }}>
                              <strong>✓ Correct Answer:</strong>{" "}
                              {q.correctAnswer || q.answer}
                            </small>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Modal for editing/adding a question */}
      {(editingQuestionId !== null || isAddingQuestion) && (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0,0,0,0.5)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 1051,
          }}
          onClick={handleCloseEditQuestion}
        >
          <div
            style={{
              backgroundColor: "white",
              borderRadius: "8px",
              maxWidth: "700px",
              width: "90%",
              maxHeight: "90vh",
              display: "flex",
              flexDirection: "column",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: "20px",
                borderBottom: "1px solid #dee2e6",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <h5 style={{ margin: 0 }}>
                {isAddingQuestion ? "Add Question" : "Edit Question"}
              </h5>
              <button
                type="button"
                className="btn-close"
                onClick={handleCloseEditQuestion}
                aria-label="Close"
              ></button>
            </div>
            <div style={{ padding: "20px", overflowY: "auto", flex: 1 }}>
              <form onSubmit={handleSaveEditedQuestion}>
                <div className="mb-3">
                  <label className="form-label">Question Title *</label>
                  <textarea
                    value={editTitle}
                    onChange={(e) => setEditTitle(e.target.value)}
                    className="form-control"
                    rows={3}
                  />
                </div>

                <div className="mb-3">
                  <label className="form-label">Topic</label>
                  <input
                    type="text"
                    value={editTopic}
                    onChange={(e) => setEditTopic(e.target.value)}
                    className="form-control"
                  />
                </div>

                <div className="mb-3">
                  <label className="form-label">Options *</label>
                  {Object.entries(editOptions).map(([key, value]) => (
                    <div key={key} className="mb-2">
                      <div
                        style={{
                          display: "flex",
                          gap: "10px",
                          alignItems: "flex-end",
                        }}
                      >
                        <div style={{ flex: 1 }}>
                          <label
                            className="form-label"
                            style={{ fontSize: "12px" }}
                          >
                            Option {key}
                          </label>
                          <input
                            type="text"
                            value={value || ""}
                            onChange={(e) =>
                              setEditOptions({
                                ...editOptions,
                                [key]: e.target.value,
                              })
                            }
                            className="form-control"
                            placeholder={`Option ${key}`}
                          />
                        </div>
                        <div
                          style={{
                            display: "flex",
                            gap: "5px",
                            alignItems: "flex-end",
                          }}
                        >
                          {/* <div>
                            <label
                              className="form-label"
                              style={{ fontSize: "12px" }}
                            >
                              Weight
                            </label>
                            <input
                              type="number"
                              value={editWeights[key] || 0}
                              onChange={(e) =>
                                setEditWeights({
                                  ...editWeights,
                                  [key]: parseInt(e.target.value) || 0,
                                })
                              }
                              className="form-control"
                              style={{ width: "70px" }}
                              min="0"
                            />
                          </div> */}
                          {Object.keys(editOptions).length > 1 && (
                            <button
                              type="button"
                              className="btn btn-sm btn-danger"
                              onClick={() => handleRemoveOption(key)}
                              style={{
                                padding: "4px 8px",
                                marginBottom: "0px",
                              }}
                            >
                              Remove
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                  <button
                    type="button"
                    className="theme-btn btn-style-one"
                    style={{
                      display: "inline-block",
                      padding: "5px 10px",
                      fontSize: "14px",
                      borderRadius: "4px",
                    }}
                    onClick={handleAddOption}
                  >
                    + Add Option
                  </button>
                </div>

                <div className="mb-3">
                  <label className="form-label">Correct Answer *</label>
                  <input
                    type="text"
                    value={editAnswer}
                    onChange={(e) => setEditAnswer(e.target.value)}
                    placeholder="Enter the key of correct answer (e.g., A)"
                    className="form-control"
                  />
                  <small className="text-muted">
                    Must match one of the option keys above
                  </small>
                </div>

                <div
                  style={{
                    display: "flex",
                    gap: "10px",
                    justifyContent: "flex-end",
                  }}
                >
                  <button
                    type="button"
                    className="btn btn-danger"
                    onClick={handleCloseEditQuestion}
                    disabled={savingQuestion}
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="theme-btn btn-style-one"
                    style={{
                      display: "inline-block",
                      padding: "10px 20px",
                      fontSize: "14px",
                      borderRadius: "4px",
                    }}
                    disabled={savingQuestion}
                  >
                    {savingQuestion ? "Saving..." : "Save Changes"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default CreateExams;
