// Skill Test Admin - Library and Question Creation
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;
  noOfQuestions?: number;
};

type QuestionOption = {
  key: string;
  text: string;
  weight: number;
};

type Question = {
  id?: string;
  questionText: string;
  topic: string;
  options: QuestionOption[];
  correctAnswer: string;
};

const CreateQuestionSet = () => {
  const skillApi = useSkillApi() as any;
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [subject, setSubject] = useState("");
  const [role, setRole] = useState("");
  const [noOfQuestions, setNoOfQuestions] = useState<number | "">(0);
  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);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);

  const [questions, setQuestions] = useState<Question[]>([
    {
      id: `q-${Date.now()}`,
      questionText: "",
      topic: "",
      options: [
        { key: "A", text: "", weight: 0 },
        { key: "B", text: "", weight: 0 },
      ],
      correctAnswer: "",
    },
  ]);

  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;
    }
    // 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();
      const normalized = (libs || []).map((l: any) => ({
        id: l.id,
        name:
          (l as any).name || l.title || l.title_en || l.subject || "Untitled",
        noOfQuestions:
          l.noOfQuestions || l.no_of_questions || l.questionCount || 0,
      }));
      setLibraries(normalized);
    } catch (err) {
      console.error("Failed to fetch libraries", err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateLibrary = async () => {
    if (!name.trim()) {
      await Swal.fire({
        icon: "warning",
        title: "Validation Error",
        text: "Library name is required.",
      });
      return;
    }
    if (!subject.trim()) {
      await Swal.fire({
        icon: "warning",
        title: "Validation Error",
        text: "Subject is required.",
      });
      return;
    }
    if (!role.trim()) {
      await Swal.fire({
        icon: "warning",
        title: "Validation Error",
        text: "Role is required.",
      });
      return;
    }
    if (!noOfQuestions || noOfQuestions <= 0) {
      await Swal.fire({
        icon: "warning",
        title: "Validation Error",
        text: "Number of questions must be greater than 0.",
      });
      return;
    }

    const isDuplicate = libraries.some(
      (lib) => lib.name.toLowerCase() === name.trim().toLowerCase()
    );
    if (isDuplicate) {
      await Swal.fire({
        icon: "error",
        title: "Validation Error",
        text: "Library name already exists",
      });
      return;
    }
    try {
      const lib = await skillApi.createLibrary({
        title: name,
        description: description || undefined,
        subject: subject || undefined,
        role: role || undefined,
        noOfQuestions:
          typeof noOfQuestions === "number" ? noOfQuestions : undefined,
      });
      if (!lib || !lib.id) {
        console.error("Invalid library response - missing id:", lib);
        // alert("Failed to create library: Invalid response from server");
        await Swal.fire({
          icon: "error",
          title: "Failed to create library",
          text: "Invalid response from server",
        });
        return;
      }
      const normalized = {
        id: lib.id,
        name: (lib as any).name || lib.title || name,
      };
      setLibraries((prev) => [normalized, ...prev]);
      setName("");
      setDescription("");
      setSubject("");
      setRole("");
      setNoOfQuestions(0);
      setSelectedLibraryId(lib.id);
      // alert("Library created successfully");
      await Swal.fire({
        icon: "success",
        title: "Library created successfully",
      });
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error("Create library failed - Full Error:", err);
      // alert("Failed to create library: " + errorMessage);
      await Swal.fire({
        icon: "error",
        title: "Failed to create library",
        text: errorMessage,
      });
    }
  };

  const handleAddQuestion = () => {
    const newQuestion: Question = {
      id: `q-${Date.now()}`,
      questionText: "",
      topic: "",
      options: [
        { key: "A", text: "", weight: 0 },
        { key: "B", text: "", weight: 0 },
      ],
      correctAnswer: "",
    };
    setQuestions([...questions, newQuestion]);
  };

  const handleRemoveQuestion = (questionId: string) => {
    if (questions.length <= 1)
      // return alert("At least one question is required");
      return Swal.fire({
        icon: "warning",
        title: "Validation Error",
        text: "At least one question is required",
      });
    setQuestions(questions.filter((q) => q.id !== questionId));
  };

  const handleQuestionChange = (
    questionId: string,
    field: keyof Question,
    value: any,
  ) => {
    setQuestions(
      questions.map((q) =>
        q.id === questionId ? { ...q, [field]: value } : q,
      ),
    );
  };

  const handleAddOption = (questionId: string) => {
    setQuestions(
      questions.map((q) => {
        if (q.id === questionId) {
          // Auto-generate the next key (A, B, C, ...)
          const currentKeys = q.options.map((opt) => opt.key);
          let nextKey = "A";
          for (let i = 0; i < 26; i++) {
            const letter = String.fromCharCode(65 + i);
            if (!currentKeys.includes(letter)) {
              nextKey = letter;
              break;
            }
          }
          return {
            ...q,
            options: [...q.options, { key: nextKey, text: "", weight: 0 }],
          };
        }
        return q;
      }),
    );
  };

  const handleRemoveOption = (questionId: string, optionIndex: number) => {
    setQuestions(
      questions.map((q) => {
        if (q.id === questionId) {
          if (q.options.length <= 1) {
            // alert("At least one option is required");
            Swal.fire({
              icon: "warning",
              title: "Validation Error",
              text: "At least one option is required",
            });
            return q;
          }
          const newOptions = q.options.filter((_, i) => i !== optionIndex);
          const correctAnswer =
            q.correctAnswer === q.options[optionIndex].key
              ? ""
              : q.correctAnswer;
          return { ...q, options: newOptions, correctAnswer };
        }
        return q;
      }),
    );
  };

  const handleOptionChange = (
    questionId: string,
    optionIndex: number,
    field: "key" | "text" | "weight",
    value: string | number,
  ) => {
    setQuestions(
      questions.map((q) => {
        if (q.id === questionId) {
          const newOptions = [...q.options];
          if (field === "weight") {
            newOptions[optionIndex][field] =
              typeof value === "number"
                ? value
                : parseInt(value as string) || 0;
          } else {
            newOptions[optionIndex][field] = value as string;
          }
          return { ...q, options: newOptions };
        }
        return q;
      }),
    );
  };

  const validateQuestion = (
    question: Question,
    index: number,
  ): string | null => {
    if (!question.questionText.trim()) {
      return `Question ${index + 1}: Enter question text`;
    }
    if (!question.topic.trim()) {
      return `Question ${index + 1}: Enter topic`;
    }
    if (!question.correctAnswer.trim()) {
      return `Question ${index + 1}: Select correct answer`;
    }

    for (let i = 0; i < question.options.length; i++) {
      const opt = question.options[i];
      if (!opt.text.trim()) {
        return `Question ${index + 1}, Option ${opt.key}: Please fill option text`;
      }
    }

    const keys = question.options.map((opt) => opt.key);
    const uniqueKeys = new Set(keys);
    if (keys.length !== uniqueKeys.size) {
      return `Question ${index + 1}: Option keys must be unique`;
    }

    if (!keys.includes(question.correctAnswer)) {
      return `Question ${index + 1}: Correct answer must match one of the option keys`;
    }

    return null;
  };

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

    for (let i = 0; i < questions.length; i++) {
      const validationError = validateQuestion(questions[i], i);
      if (validationError) {
        // return alert(validationError);
        await Swal.fire({ icon: "error", text: validationError });
      }
    }

    try {
      setLoading(true);
      const payloads: any[] = [];
      const errors: string[] = [];

      // Prepare payloads
      for (let idx = 0; idx < questions.length; idx++) {
        const question = questions[idx];
        const optionsObj: { [key: string]: string } = {};
        const weightsObj: { [key: string]: number } = {};

        question.options.forEach((opt) => {
          optionsObj[opt.key] = opt.text;
          weightsObj[opt.key] = opt.weight;
        });

        const payload = {
          skillQuestionLibraryId: selectedLibraryId,
          questionText: question.questionText,
          topic: question.topic,
          options: optionsObj,
          answer: question.correctAnswer,
          weights: weightsObj,
          isActive: true,
        };
        payloads.push(payload);
      }

      // Send bulk request
      try {
        const createdQuestions =
          await skillApi.createMultipleQuestions(payloads);
        const successCount = createdQuestions.length;

        await Swal.fire({
          icon: "success",
          text: `All ${successCount} questions saved successfully!`,
        });
        setQuestions([
          {
            id: `q-${Date.now()}`,
            questionText: "",
            topic: "",
            options: [
              { key: "A", text: "", weight: 0 },
              { key: "B", text: "", weight: 0 },
            ],
            correctAnswer: "",
          },
        ]);
        // Redirect to create-exam page after successful save
        router.push("/dashboard/skill-test/create-exam");
      } catch (err: any) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        console.error("Failed to save questions:", err);
        await Swal.fire({
          icon: "error",
          text: `Failed to save questions: ${errorMsg}`,
        });
      }
    } catch (err) {
      const errMsg = err instanceof Error ? err.message : String(err);
      console.error("Save questions failed:", errMsg, err);
      // alert("Failed to save questions: " + errMsg);
      await Swal.fire({
        icon: "error",
        text: `Failed to save questions: ${errMsg}`,
      });
    } finally {
      setLoading(false);
    }
  };

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

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

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

                  <div className="mb-3">
                    <label className="form-label">Library Name *</label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      placeholder="Library name"
                      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">Subject *</label>
                    <input
                      type="text"
                      value={subject}
                      onChange={(e) => {
                        const val = e.target.value;
                        if (/^[a-zA-Z\s]*$/.test(val)) setSubject(val);
                      }}
                      placeholder="Subject (e.g., Programming)"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Role *</label>
                    <input
                      type="text"
                      value={role}
                      onChange={(e) => {
                        const val = e.target.value;
                        if (/^[a-zA-Z\s]*$/.test(val)) setRole(val);
                      }}
                      placeholder="Role (e.g., Frontend Developer)"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Number of Questions *</label>
                    <input
                      type="number"
                      value={noOfQuestions}
                      onChange={(e) => {
                        const val = e.target.value;
                        setNoOfQuestions(val === "" ? "" : parseInt(val));
                      }}
                      placeholder="Number of questions"
                      min={1}
                      className="form-control"
                    />
                  </div>

                  <button
                    className="theme-btn btn-style-one w-100"
                    onClick={handleCreateLibrary}
                  >
                    Create Library
                  </button>

                  <div className="mb-3 mt-4">
                    <label className="form-label">
                      Or Select Existing 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.map((lib) => (
                        <option key={lib.id} value={lib.id}>
                          {lib.name}
                        </option>
                      ))}
                    </select>
                    {selectedLibraryId && (
                      <small className="text-success d-block mt-2">
                        ✓ Library selected for adding questions
                      </small>
                    )}
                  </div>
                </div>
              </div>

              {/* Right Column: Total Questions - Only visible when library is selected */}
              {selectedLibraryId ? (
                <div className="col-lg-8">
                  <div className="ls-widget p-4">
                    <div className="d-flex justify-content-between align-items-center mb-4">
                      <h5>Total Questions ({questions.length})</h5>
                      <button
                        type="button"
                        className="theme-btn btn-style-one"
                        style={{
                          display: "inline-block",
                          padding: "10px 20px",
                          fontSize: "14px",
                          borderRadius: "4px",
                        }}
                        onClick={handleAddQuestion}
                      >
                        + Add Another Question
                      </button>
                    </div>

                    {[...questions].reverse().map((question, qIndex) => (
                      <div
                        key={question.id}
                        className="question-form mb-4 p-3 border rounded"
                        style={{ backgroundColor: "#f8f9fa" }}
                      >
                        <div className="d-flex justify-content-between align-items-center mb-3">
                          <h6 className="mb-0">
                            Question {questions.length - qIndex}
                          </h6>
                          {questions.length > 1 && (
                            <button
                              type="button"
                              className="btn btn-danger btn-sm"
                              onClick={() => handleRemoveQuestion(question.id!)}
                            >
                              Remove Question
                            </button>
                          )}
                        </div>

                        <div className="mb-3">
                          <label className="form-label">Topic *</label>
                          <input
                            type="text"
                            value={question.topic}
                            onChange={(e) =>
                              handleQuestionChange(
                                question.id!,
                                "topic",
                                e.target.value,
                              )
                            }
                            placeholder="Enter topic (e.g., Arrays, Functions)"
                            className="form-control"
                          />
                        </div>

                        <div className="mb-3">
                          <label className="form-label">Question Text *</label>
                          <textarea
                            value={question.questionText}
                            onChange={(e) =>
                              handleQuestionChange(
                                question.id!,
                                "questionText",
                                e.target.value,
                              )
                            }
                            placeholder="Enter your question"
                            rows={3}
                            className="form-control"
                          />
                        </div>

                        <div className="mb-3">
                          <label className="form-label">Options *</label>
                          {question.options.map((option, optIndex) => (
                            <div key={optIndex} className="mb-2">
                              <div
                                style={{
                                  display: "flex",
                                  gap: "10px",
                                  alignItems: "flex-end",
                                }}
                              >
                                <div style={{ flex: 1 }}>
                                  <label
                                    className="form-label"
                                    style={{ fontSize: "12px" }}
                                  >
                                    Option {option.key}
                                  </label>
                                  <input
                                    type="text"
                                    value={option.text}
                                    onChange={(e) =>
                                      handleOptionChange(
                                        question.id!,
                                        optIndex,
                                        "text",
                                        e.target.value,
                                      )
                                    }
                                    className="form-control"
                                    placeholder={`Option ${option.key}`}
                                  />
                                </div>
                                <div
                                  style={{
                                    display: "flex",
                                    gap: "5px",
                                    alignItems: "flex-end",
                                  }}
                                >
                                  {question.options.length > 1 && (
                                    <button
                                      type="button"
                                      className="btn btn-sm btn-danger"
                                      onClick={() =>
                                        handleRemoveOption(
                                          question.id!,
                                          optIndex,
                                        )
                                      }
                                      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(question.id!)}
                          >
                            + Add Option
                          </button>
                        </div>

                        <div className="mb-3">
                          <label className="form-label">Correct Answer *</label>
                          <input
                            type="text"
                            value={question.correctAnswer}
                            onChange={(e) =>
                              handleQuestionChange(
                                question.id!,
                                "correctAnswer",
                                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>
                    ))}

                    <button
                      className="theme-btn btn-style-one w-100"
                      onClick={handleSaveAllQuestions}
                      disabled={loading}
                    >
                      {loading
                        ? "Saving..."
                        : `Save All Questions (${questions.length})`}
                    </button>
                  </div>
                </div>
              ) : (
                <div className="col-lg-8">
                  <div className="ls-widget p-4 text-center">
                    <div style={{ padding: "60px 20px" }}>
                      <div
                        style={{
                          fontSize: "48px",
                          color: "#dee2e6",
                          marginBottom: "20px",
                        }}
                      >
                        📚
                      </div>
                      <h5 style={{ color: "#6c757d", marginBottom: "10px" }}>
                        Select a Library First For Adding Questions
                      </h5>
                      <p style={{ color: "#6c757d", marginBottom: "0" }}>
                        Please select an existing library from the dropdown on
                        the left to start adding questions.
                      </p>
                    </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>
              <button
                type="button"
                className="btn-close"
                onClick={handleCloseViewQuestions}
                aria-label="Close"
              ></button>
            </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>
              ) : (
                <div>
                  {viewingLibraryQuestions.map((q: any, idx: number) => (
                    <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}
                        </h6>
                      </div>
                      {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]) => (
                              <div
                                key={key}
                                style={{
                                  display: "flex",
                                  alignItems: "center",
                                  marginBottom: "10px",
                                  padding: "10px",
                                  borderRadius: "4px",
                                  backgroundColor:
                                    q.correctAnswer === key || q.answer === key
                                      ? "rgba(25, 135, 84, 0.1)"
                                      : "#fff",
                                  border:
                                    q.correctAnswer === key || q.answer === key
                                      ? "1px solid #198754"
                                      : "1px solid #dee2e6",
                                }}
                              >
                                <span
                                  className={`badge ${q.correctAnswer === key || q.answer === key ? "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>
      )}
    </>
  );
};

export default CreateQuestionSet;
