Hkoradiya123
Serve frontend and backend from one Space
38ee1b6
Raw History Blame Contribute Delete
23.4 kB
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 (
<div className="flex flex-col items-center justify-center h-full space-y-4">
<p className="text-muted-foreground">No document to preview.</p>
<Button onClick={() => navigate("/app/generate")}>Go to Generator</Button>
</div>
);
}
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 (
<div className="flex flex-col items-center justify-center p-20 min-h-[600px] bg-card rounded-2xl border border-border mt-10 shadow-sm">
<Loader2 className="animate-spin text-primary h-10 w-10 mb-4" />
<p className="text-muted-foreground font-medium">Securing session...</p>
</div>
);
}
if (userHasPin && !isVerified) {
return (
<div className="flex flex-col items-center justify-center p-20 min-h-[600px] bg-card rounded-2xl border border-border mt-10 shadow-xl border-t-4 border-t-primary">
<div className="w-20 h-20 bg-primary/10 rounded-full flex items-center justify-center text-primary mb-6 shadow-inner ring-4 ring-primary/5">
<Lock size={40} className="drop-shadow-sm" />
</div>
<h2 className="text-2xl font-bold mb-3 tracking-tight">Paper is Encrypted</h2>
<p className="text-muted-foreground text-center max-w-sm mb-8 leading-relaxed">
This document is protected by your Exam PIN. Please unlock it to view the content and download the PDF.
</p>
<Button
className="h-12 px-10 text-lg font-bold shadow-lg shadow-primary/20 hover:scale-[1.05] transition-transform"
onClick={() => setIsPinModalOpen(true)}
>
Unlock Paper
</Button>
<ExamPinModal
isOpen={isPinModalOpen}
onClose={() => setIsPinModalOpen(false)}
onVerified={handleVerifySuccess}
title="Unlock Exam Paper"
/>
</div>
);
}
return (
<div className="max-w-5xl mx-auto py-6 space-y-6">
<div className="sticky top-0 z-50 bg-background/80 backdrop-blur-md p-4 rounded-b-xl border-b border-border shadow-sm flex items-center justify-between mb-6 -mx-4 md:mx-0 md:rounded-xl">
<Button variant="ghost" onClick={() => navigate('/app/generate')} className="text-muted-foreground hover:text-foreground">
<ArrowLeft className="mr-2" size={20} /> Back
</Button>
<div className="flex gap-3">
<Button variant="outline" className="gap-2 border-border hover:bg-muted/50" onClick={() => window.print()}>
<Printer size={18} /> Print
</Button>
<Button className="gap-2 glow-border" onClick={handleDownloadPDF} disabled={isDownloading}>
{isDownloading ? <Loader2 size={18} className="animate-spin" /> : <Download size={18} />}
{isDownloading ? "Exporting..." : "Export PDF"}
</Button>
</div>
</div>
<motion.div
initial={{ opacity: 0, scale: 0.98 }}
animate={{ opacity: 1, scale: 1 }}
className="bg-card shadow-xl rounded-2xl border border-border p-8 md:p-14 min-h-[800px]"
>
<div className="text-center border-b-2 border-primary/50 pb-8 mb-10">
<h1 className="text-4xl font-bold mb-3 uppercase tracking-wider text-foreground">
{formData.title || paperResult?.title || "Examination"}
</h1>
<p className="text-muted-foreground text-xl mb-6">Subject: {formData.subject || 'General'} | Grade: {formData.classGrade || 'N/A'}</p>
<div className="flex justify-center flex-wrap gap-4 text-sm font-semibold">
<span className="bg-muted px-4 py-2 rounded-lg border border-border">Time Allowed: {formData.duration} Mins</span>
<span className="bg-muted px-4 py-2 rounded-lg border border-border">Sections: {paperResult?.sections?.length || 0}</span>
<span className="bg-muted px-4 py-2 rounded-lg border border-border">
Total Marks: {formData.totalMarks || 100}
</span>
</div>
</div>
<div className="space-y-10">
{formData.instructions && (
<div className="mb-8 p-4 bg-muted/30 border border-border rounded-xl text-sm italic text-muted-foreground whitespace-pre-line">
<span className="font-semibold text-foreground not-italic block mb-2">General Instructions:</span>
{formData.instructions}
</div>
)}
{paperResult && paperResult.sections ? (
paperResult.sections.map((section, sIndex) => (
<div key={sIndex} className="mb-12">
<div className="mb-6 bg-muted/20 p-4 border-l-4 border-primary rounded-r-lg">
<h3 className="text-2xl font-bold mb-1">{section.section_name}</h3>
<p className="text-sm text-muted-foreground font-medium">{section.instructions}</p>
</div>
<div className="space-y-8 pl-2">
{section.questions.map((q, qIndex) => (
<div key={qIndex} className="group relative flex gap-4 p-4 -ml-4 rounded-xl border-2 border-transparent hover:border-dashed hover:border-primary/40 hover:bg-primary/5 transition-all">
<div className="font-bold text-lg mt-0.5 min-w-[32px]">Q{qIndex + 1}.</div>
<div className="flex-1">
<div className="flex justify-between items-start gap-4">
<div className="flex-1">
<p className={cn(
"text-lg leading-relaxed text-foreground/90 font-medium transition-opacity",
loadingQuestion === `${sIndex}-${qIndex}` && "opacity-30"
)}>
{q.question_text}
</p>
{q.internal_choice_question_text && (
<div className={cn(
"mt-4 transition-opacity",
loadingQuestion === `${sIndex}-${qIndex}` && "opacity-30"
)}>
<div className="flex items-center gap-4 my-2 opacity-50">
<div className="h-px bg-border flex-1"></div>
<span className="text-xs font-bold uppercase tracking-wider">OR</span>
<div className="h-px bg-border flex-1"></div>
</div>
<p className="text-lg leading-relaxed text-foreground/90 font-medium">
{q.internal_choice_question_text}
</p>
</div>
)}
</div>
{q.marks && (
<span className="shrink-0 text-sm font-bold bg-muted px-2 py-1 border border-border rounded">[{q.marks}]</span>
)}
</div>
{q.options && q.options.length > 0 && (
<div className="grid md:grid-cols-2 gap-4 mt-5">
{q.options.map((opt, j) => (
<div key={j} className="flex items-start gap-3 p-3 rounded-lg border border-border/60 bg-muted/10">
<div className="h-5 w-5 rounded-full border-2 border-primary/50 shrink-0 flex items-center justify-center mt-0.5">
<span className="text-[10px] font-bold text-primary">{String.fromCharCode(65 + j)}</span>
</div>
<span className="text-base text-foreground/80">{opt}</span>
</div>
))}
</div>
)}
<div className="flex flex-wrap gap-2 mt-4">
{q.bloom_level && (
<span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-accent/10 text-accent px-2 py-1 rounded">
{q.bloom_level}
</span>
)}
{q.estimated_time_mins && (
<span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-blue-500/10 text-blue-500 px-2 py-1 rounded">
{q.estimated_time_mins} mins
</span>
)}
{q.chapter && (
<span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-purple-500/10 text-purple-500 px-2 py-1 rounded line-clamp-1 max-w-[200px]" title={q.chapter}>
CH: {q.chapter}
</span>
)}
{q.competency && (
<span className="inline-block text-[11px] uppercase tracking-wider font-semibold bg-emerald-500/10 text-emerald-500 px-2 py-1 rounded line-clamp-1 max-w-[200px]" title={q.competency}>
{q.competency}
</span>
)}
</div>
{(q.correct_answer || q.marking_scheme) && (
<div className="mt-4 p-4 rounded-lg bg-orange-500/5 border border-orange-500/20">
{q.correct_answer && (
<div className="mb-2">
<span className="text-xs font-bold uppercase text-orange-600 dark:text-orange-400 block mb-1">Answer Key:</span>
<p className="text-sm text-foreground/80">{q.correct_answer}</p>
</div>
)}
{q.marking_scheme && (
<div>
<span className="text-xs font-bold uppercase text-orange-600 dark:text-orange-400 block mb-1">Marking Scheme:</span>
<p className="text-sm text-foreground/80 whitespace-pre-line">{q.marking_scheme}</p>
</div>
)}
</div>
)}
<div className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity bg-card shadow-lg border border-border rounded-lg p-1 flex flex-col gap-1">
<button
onClick={() => handleRegenerateSpecificQuestion(sIndex, qIndex)}
disabled={loadingQuestion === `${sIndex}-${qIndex}`}
className="p-2 text-muted-foreground hover:text-primary hover:bg-primary/10 rounded-md transition-colors disabled:opacity-50"
title="Regenerate this specific question"
>
{loadingQuestion === `${sIndex}-${qIndex}` ? <Loader2 size={16} className="animate-spin" /> : <RotateCcw size={16} />}
</button>
<button
onClick={() => handleCopyQuestion(q.question_text, `${sIndex}-${qIndex}`)}
className="p-2 text-muted-foreground hover:text-accent hover:bg-accent/10 rounded-md transition-colors"
title="Copy text"
>
{copiedIndex === `${sIndex}-${qIndex}` ? <CheckCircle2 size={16} className="text-emerald-500" /> : <Copy size={16} />}
</button>
</div>
</div>
</div>
))}
</div>
</div>
))
) : (
<div className="space-y-12 animate-pulse py-10">
{[1, 2, 3].map(i => (
<div key={i} className="mb-12">
<div className="mb-6 bg-muted/20 p-4 border-l-4 border-muted rounded-r-lg">
<div className="h-6 bg-muted rounded w-1/4 mb-2"></div>
<div className="h-4 bg-muted/60 rounded w-1/2"></div>
</div>
<div className="space-y-8 pl-2">
{[1, 2].map(j => (
<div key={j} className="flex gap-4 p-4">
<div className="h-6 w-8 bg-muted rounded mt-1"></div>
<div className="flex-1 space-y-4">
<div className="h-5 bg-muted rounded w-full"></div>
<div className="h-5 bg-muted rounded w-5/6"></div>
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
</div>
</motion.div>
</div>
);
}