import React, { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import { ArrowLeft, Download, Printer, RotateCcw, Copy, CheckCircle2, Loader2, Lock } from "lucide-react";
import { Button } from "../../components/ui/Button";
import { cn } from "../../utils/cn";
import { ExamPinModal } from "../../components/ui/ExamPinModal";
import { supabase } from "../../utils/supabaseClient";
import { API_BASE_URL } from "../../utils/api";
export default function Preview() {
const location = useLocation();
const navigate = useNavigate();
const { formData, sectionsData, generatedResult } = location.state || {};
const [paperResult, setPaperResult] = useState(generatedResult);
const [copiedIndex, setCopiedIndex] = useState(null);
const [isDownloading, setIsDownloading] = useState(false);
const [loadingQuestion, setLoadingQuestion] = useState(null); // format: "sIndex-qIndex"
// Exam PIN Verification States
const [isVerified, setIsVerified] = useState(false);
const [isPinModalOpen, setIsPinModalOpen] = useState(false);
const [userHasPin, setUserHasPin] = useState(false);
const [verifiedPin, setVerifiedPin] = useState("");
const [isInitialLoad, setIsInitialLoad] = useState(true);
React.useEffect(() => {
const checkUserPin = async () => {
try {
const { data: { session } } = await supabase.auth.getSession();
const response = await fetch(`${API_BASE_URL}/api/profile`, {
method: 'GET',
headers: { 'Authorization': `Bearer ${session?.access_token}` }
});
if (response.ok) {
const data = await response.json();
if (data.has_exam_password) {
setUserHasPin(true);
setIsPinModalOpen(true);
} else {
setIsVerified(true);
}
}
} catch (error) {
console.error("Error checking PIN status:", error);
setIsVerified(true); // Fallback to avoid locking user out on error
} finally {
setIsInitialLoad(false);
}
};
checkUserPin();
}, []);
// If no state exists (direct access), send back to generate
if (!formData) {
return (
No document to preview.
);
}
const handleDownloadPDF = async () => {
setIsDownloading(true);
try {
const { data: { session } } = await supabase.auth.getSession();
const res = await fetch(`${API_BASE_URL}/download`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session?.access_token}`
},
body: JSON.stringify({
form_data: formData,
generated_result: generatedResult,
password: verifiedPin
})
});
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${formData.title || 'ExamCraft_Paper'}.pdf`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error("Download failed", error);
alert("Download failed. Please try again.");
} finally {
setIsDownloading(false);
}
};
const handleCopyQuestion = (text, index) => {
navigator.clipboard.writeText(text);
setCopiedIndex(index);
setTimeout(() => setCopiedIndex(null), 2000);
};
const handleRegenerateSpecificQuestion = async (sectionIndex, questionIndex) => {
const key = `${sectionIndex}-${questionIndex}`;
setLoadingQuestion(key);
try {
const { data: { session } } = await supabase.auth.getSession();
const res = await fetch(`${API_BASE_URL}/regenerate-question`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session?.access_token}`
},
body: JSON.stringify({
question_data: paperResult.sections[sectionIndex].questions[questionIndex],
paper_id: paperResult.paper_id,
source_content: formData?.content_preview || "" // We might need to pass this or handle it backend
})
});
if (!res.ok) throw new Error("Regeneration failed");
const newQuestion = await res.json();
if (newQuestion.error) throw new Error(newQuestion.error);
// Update local state
const updatedSections = [...paperResult.sections];
updatedSections[sectionIndex].questions[questionIndex] = newQuestion;
const updatedPaper = { ...paperResult, sections: updatedSections };
setPaperResult(updatedPaper);
// Persist the change to the database
if (paperResult.paper_id) {
await fetch(`${API_BASE_URL}/api/exam_papers/${paperResult.paper_id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${session?.access_token}`
},
body: JSON.stringify({
content: updatedPaper
})
});
}
} catch (error) {
console.error("Regeneration error:", error);
alert("Failed to regenerate question. Please try again.");
} finally {
setLoadingQuestion(null);
}
};
const handleVerifySuccess = (pin) => {
setVerifiedPin(pin);
setIsVerified(true);
};
if (isInitialLoad) {
return (
);
}
if (userHasPin && !isVerified) {
return (
Paper is Encrypted
This document is protected by your Exam PIN. Please unlock it to view the content and download the PDF.
setIsPinModalOpen(false)}
onVerified={handleVerifySuccess}
title="Unlock Exam Paper"
/>
);
}
return (
{formData.title || paperResult?.title || "Examination"}
Subject: {formData.subject || 'General'} | Grade: {formData.classGrade || 'N/A'}
Time Allowed: {formData.duration} Mins
Sections: {paperResult?.sections?.length || 0}
Total Marks: {formData.totalMarks || 100}
{formData.instructions && (
General Instructions:
{formData.instructions}
)}
{paperResult && paperResult.sections ? (
paperResult.sections.map((section, sIndex) => (
{section.section_name}
{section.instructions}
{section.questions.map((q, qIndex) => (
Q{qIndex + 1}.
{q.question_text}
{q.internal_choice_question_text && (
{q.internal_choice_question_text}
)}
{q.marks && (
[{q.marks}]
)}
{q.options && q.options.length > 0 && (
{q.options.map((opt, j) => (
{String.fromCharCode(65 + j)}
{opt}
))}
)}
{q.bloom_level && (
{q.bloom_level}
)}
{q.estimated_time_mins && (
{q.estimated_time_mins} mins
)}
{q.chapter && (
CH: {q.chapter}
)}
{q.competency && (
{q.competency}
)}
{(q.correct_answer || q.marking_scheme) && (
{q.correct_answer && (
Answer Key:
{q.correct_answer}
)}
{q.marking_scheme && (
Marking Scheme:
{q.marking_scheme}
)}
)}
))}
))
) : (
{[1, 2, 3].map(i => (
))}
)}
);
}