import React, { useEffect, useState, useMemo } from "react";
import { FullScreen, useFullScreenHandle } from "react-full-screen";
import { useGetTestSeriesByIdQuery } from "../manageTests/TestSeriesSlice";
import { useTestState } from "../testSlice";
import {
useGetTestPaperByIdQuery,
useGetTestPapersQuery,
useUploadQuestionMutation,
} from "./testPaperApiSlice";
// List of supported languages for questions and options
const languages = ["english", "hindi", "spanish", "french"];
const MockTestGenerator = () => {
// Fetching testPaperId and testSeriesId from the testSlice
const { testPaperId } = useTestState();
const {
data: TestPaper,
isLoading,
isSuccess,
isError,
error,
} = useGetTestPaperByIdQuery(testPaperId);
useEffect(() => {
console.log(TestPaper)
},[TestPaper])
// State for managing sections
const [sections, setSections] = useState(TestPaper?.data?.sections);
const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
const [currentLanguage, setCurrentLanguage] = useState(languages[0]);
const currentSection =
TestPaper?.data?.sections[currentSectionIndex]?.sectionName;
const questionsForCurrentSection = useMemo(
() => (currentSection ? currentSection.noOfQuestions : 0),
[currentSection]
);
console.log(currentSection);
const getInitialQuestions = () =>
languages.map((lang) => ({ type: lang, value: "" }));
const getInitialOptions = () => {
const newOptions = languages.flatMap((lang) =>
Array.from({ length: 5 }, (_, index) => ({
optionId: opt${index + 1},
type: lang,
value: "",
}))
);
return newOptions;
};
// useEffect(() => {
// setQuestion(getInitialQuestions());
// setOptions(getInitialOptions());
// }, [currentLanguage]);
// ...
// State for managing the current question being created
const [selectedQuestions, setSelectedQuestions] = useState([]);
const [question, setQuestion] = useState(getInitialQuestions());
const [options, setOptions] = useState(() => getInitialOptions());
const [correctOption, setCorrectOption] = useState(options[0].optionId);
const [marks, setMarks] = useState(2);
const [currentQuestionNo, setCurrentQuestionNo] = useState(1);
// State to store questions after submission
const [storedQuestions, setStoredQuestions] = useState([]);
console.log("question", question);
console.log("options", options);
const [upload] = useUploadQuestionMutation();
// Hook for handling fullscreen mode
const handle = useFullScreenHandle();
const handleQuestionSelect = (questionNo) => {
setSelectedQuestions((prevSelected) =>
prevSelected.includes(questionNo)
? prevSelected.filter((selectedNo) => selectedNo !== questionNo)
: [...prevSelected, questionNo]
);
};
// Memoized function to check if a question is selected
const isQuestionSelected = useMemo(
() => (questionNo) => selectedQuestions.includes(questionNo),
[selectedQuestions]
);
// Function to handle changes in question and option values
const handleOptionChange = (index, language, value, isQuestion) => {
if (isQuestion) {
setQuestion((prevQuestion) =>
prevQuestion.map((q) => (q.type === language ? { ...q, value } : q))
);
}
const existingQuestion = storedQuestions[currentSection.name]?.find(
(q) => q.language === language
);
if (existingQuestion) {
// If the question already exists for the selected language, update it in the storedQuestions state
setStoredQuestions((prevStoredQuestions) => ({
...prevStoredQuestions,
[currentSection.name]: prevStoredQuestions[currentSection.name].map(
(q) => (q.language === language ? { ...q, question: value } : q)
),
}));
} else {
setOptions((prevOptions) =>
prevOptions.map((option, i) =>
i === index ? { ...option, value } : option
)
);
}
};
// Function to reset the form after question submission
const resetForm = () => {
setQuestion(getInitialQuestions());
setOptions(getInitialOptions());
setCorrectOption(options[0].optionId);
setMarks(2);
setCurrentQuestionNo((prevQuestionNo) => prevQuestionNo + 1);
};
// Function to clear the form and reset the question and option values
const handleClearForm = () => {
setQuestion((prevQuestion) =>
prevQuestion.map((q) =>
q.type === currentLanguage ? { ...q, value: "" } : q
)
);
setOptions((prevOptions) =>
prevOptions.map((option, i) => {
if (option.type === currentLanguage) {
return { ...option, value: "" };
}
return option;
})
);
};
// Function to set the current section based on its index
const handleSetSection = (sectionIndex) => {
setCurrentSectionIndex(sectionIndex);
};
const handleStoreQuestion = async (e) => {
e.preventDefault();
if (selectedQuestions.length >= questionsForCurrentSection) {
alert(
`You have reached the maximum allowed questions (${questionsForCurrentSection}) for this section: ${currentSection.name}`
);
return;
}
const formattedQuestion = {
sectionName: currentSection,
questionNo: currentQuestionNo,
question: question.reduce((acc, q) => {
if (q.type === currentLanguage) {
acc[q.type] = q.value;
}
return acc;
}, {}),
options: options.reduce((acc, opt) => {
if (opt.type === currentLanguage) {
acc[opt.type] = acc[opt.type] || [];
acc[opt.type].push(opt.value);
}
return acc;
}, {}),
correctOption: {
[currentLanguage]: options.findIndex(
(opt) => opt.optionId === correctOption
),
},
marks: marks,
};
console.log("Formatted Question:", formattedQuestion);
try {
const result = await upload({ formattedQuestion, testPaperId });
console.log("Question uploaded successfully!", result);
} catch (error) {
console.error("Error uploading question:", error);
}
};
const getQuestionForm = (questionNo) => {
return (
{/* Question input field /}
Question No: {questionNo}
{currentLanguage && (
Enter Question (
{currentLanguage.charAt(0).toUpperCase() +
currentLanguage.slice(1)}
):
<textarea
className="border border-gray-300 p-2 rounded-lg w-full"
value={
storedQuestions[currentSection.name]?.find(
(q) => q.language === currentLanguage
)?.question ||
question.find((q) => q.type === currentLanguage)?.value || // Use the current language as the key
""
}
onChange={(e) =>
handleOptionChange(
question, // Use question directly as an object
currentLanguage,
e.target.value,
true
)
}
rows={8}
required
/>
)}
{/ Options input fields /}
{options.map((option, index) => {
if (option.type !== currentLanguage) {
return null;
}
const optionIndex = index % 5;
return (
<input
type="text"
value={
storedQuestions[currentSection.name]?.find(
(q) =>
q.questionNo === currentQuestionNo &&
q.language === option.type
)?.options[optionIndex]?.value ||
option.value ||
""
}
onChange={(e) =>
handleOptionChange(index, option.type, e.target.value, false)
}
className="block p-2.5 mb-4 w-full z-20 text-sm text-gray-900 bg-gray-200 dark:bg-main-dark-bg rounded-r-lg border-l-2 border-blue-500 dark:border-secondary-dark-bg dark:text-white dark:focus:border-blue-500 focus:ring-blue-500 focus:border-blue-500 focus:outline-none hover:bg-gray-100 dark:hover:bg-secondary-dark-bg"
placeholder={Option ${optionIndex + 1}}
required
/>
);
})}
);
};
// JSX for displaying the question viewer
const questionViewer = (
{Array.from({
length: TestPaper?.data?.sections[currentSectionIndex]?.questionLimit,
// length:20
}).map((_, index) => {
const questionNo = index + 1;
return (
<div
key={questionNo}
className={flex items-center justify-center h-8 rounded-lg cursor-pointer ${ isQuestionSelected(questionNo) ? "bg-green-500 text-white" : "bg-gray-200 hover:bg-gray-300" }}
onClick={() => {
setCurrentQuestionNo(questionNo);
handleQuestionSelect(questionNo);
}}
>
{questionNo}
);
})}
);
return (
{TestPaper && (
<div className=" " style={{ maxHeight: "4vh" }}>
{TestPaper?.data?.testInfo?.test}
{TestPaper?.data?.title}
Enter fullscreen
{/ Form for creating and submitting questions /}
{/ Question input form /}
{/ Section and marks information /}
Section :
{/ {currentSection.name} /}dobriyal
Marks:
1
{/ Language selection */}
{languages.map((lang) => (
<button
key={lang}
type="button"
className={px-4 py-2 m-1 text-xs font-medium rounded-lg ${ currentLanguage === lang ? "bg-orange-500 text-white" : "" }}
onClick={() => setCurrentLanguage(lang)}
>
{lang.charAt(0).toUpperCase() + lang.slice(1)}
))}
{/* Current question number */}
{/* <div className="p-4">
<span className="font-semibold">Question No:</span>
<span className="font-semibold">{currentQuestionNo}</span>
</div> */}
{/* Question input field */}
{getQuestionForm(currentQuestionNo)}
{/* Buttons for clearing and submitting the question */}
<div className="flex justify-end pb-6 mx-4">
<button
type="button"
className="bg-red-500 text-white py-2 px-4 rounded-lg mr-5"
onClick={handleClearForm}
>
Clear
</button>
<button
type="submit"
className="bg-blue-500 text-white py-2 px-4 rounded-lg"
// onClick={() => handleStoreQuestion}
>
Submit Question
</button>
</div>
</div>
</form>
{/* Sidebar for selecting sections and displaying question viewer */}
<div className="bg-gray-100 p-4 rounded-lg w-80">
<h2 className="text-xl font-semibold mb-4">
{/* {TestPaper.testSeriesName} Paper Generator */}
</h2>
<div className="flex mb-4 justify-between gap-3">
{TestPaper?.data?.sections?.map((section, index) => (
<div
key={section._id}
className={`flex items-center justify-center h-8 px-2 rounded-lg cursor-pointer ${
currentSectionIndex === index
? "bg-blue-500 text-white"
: "bg-gray-200 hover:bg-gray-300"
}`}
onClick={() => handleSetSection(index)}
>
{section.sectionName}
</div>
))}
</div>
{/* Render the question viewer */}
{questionViewer}
</div>
</div>
</div>
)}
</FullScreen>
);
};
export default MockTestGenerator;