import { useState } from "react"; import { useMutation } from "@tanstack/react-query"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Sparkles, Loader2, Trash2 } from "lucide-react"; import type { ExamModule } from "@/types"; import { generationService } from "@/services/generation.service"; import { useToast } from "@/hooks/use-toast"; type ExerciseRow = { title?: string; description?: string; marks?: number }; function exerciseLabel(ex: unknown, index: number): ExerciseRow { if (ex && typeof ex === "object") { const o = ex as Record; return { title: typeof o.title === "string" ? o.title : `Exercise ${index + 1}`, description: typeof o.description === "string" ? o.description : undefined, marks: typeof o.marks === "number" ? o.marks : typeof o.marks === "string" ? Number(o.marks) : undefined, }; } return { title: String(ex) }; } export default function AiGeneratorModal() { const [open, setOpen] = useState(false); const [moduleType, setModuleType] = useState("reading"); const [difficulty, setDifficulty] = useState("b2"); const [count, setCount] = useState(5); const [topic, setTopic] = useState(""); const [localExercises, setLocalExercises] = useState(null); const { toast } = useToast(); const generateMutation = useMutation({ mutationFn: () => generationService.generate(moduleType, { title: topic.trim() || `${moduleType} practice set`, difficulty, count, }), onSuccess: (res) => { setLocalExercises(Array.isArray(res.exercises) ? res.exercises : []); }, onError: (err: Error) => { toast({ variant: "destructive", title: "Generation failed", description: err.message || "Could not generate exercises.", }); }, }); const handleGenerate = () => { setLocalExercises(null); generateMutation.mutate(); }; const generated = localExercises; const handleRemove = (index: number) => { setLocalExercises((prev) => (prev ? prev.filter((_, i) => i !== index) : null)); }; return ( { setOpen(v); if (!v) { setLocalExercises(null); generateMutation.reset(); } }} > AI Assignment Generator {!generated ? (
setCount(Number(e.target.value) || 1)} />
setTopic(e.target.value)} />
) : (

AI generated {generated.length} assignments. Edit or remove before saving.

{generated.map((item, i) => { const row = exerciseLabel(item, i); return (

{row.title}

{row.description && (

{row.description}

)} {row.marks !== undefined && !Number.isNaN(row.marks) && (

{row.marks} marks

)}
); })}
)}
); }