"use client"; import { Question, QuestionMode } from "@/types"; import { AnimatePresence, motion } from "framer-motion"; import { useEffect, useState } from "react"; interface QuestionsDashboardProps { onBack: () => void; } const NORMAL_CATEGORIES = [ "Brain", "Émotions", "Corps", "Actions", "Relations", "Sécurité", "Créativité", "Clôture", ]; const CRISIS_CATEGORIES = [ "Sécurité", "Ancrage", "Besoins", "Émotions", "Respiration", "Pensées", "Soutien", "Action", "Ressources", "Récupération", ]; export default function QuestionsDashboard({ onBack, }: QuestionsDashboardProps) { const [questions, setQuestions] = useState([]); const [loading, setLoading] = useState(true); const [activeMode, setActiveMode] = useState("normal"); const [editingQuestion, setEditingQuestion] = useState( null ); const [isAdding, setIsAdding] = useState(false); const [newQuestion, setNewQuestion] = useState({ category: "", question: "", }); const [customCategory, setCustomCategory] = useState(""); useEffect(() => { fetchQuestions(); }, []); const fetchQuestions = async () => { try { const response = await fetch("/api/questions"); const data = await response.json(); setQuestions(data); } catch (error) { console.error("Error fetching questions:", error); } finally { setLoading(false); } }; const addQuestion = async () => { const category = newQuestion.category === "__custom__" ? customCategory : newQuestion.category; if (!category.trim() || !newQuestion.question.trim()) return; try { const response = await fetch("/api/questions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ category, question: newQuestion.question, mode: activeMode, }), }); if (response.ok) { const created = await response.json(); setQuestions([...questions, created]); setNewQuestion({ category: "", question: "" }); setCustomCategory(""); setIsAdding(false); } } catch (error) { console.error("Error adding question:", error); } }; const updateQuestion = async () => { if (!editingQuestion) return; try { const response = await fetch("/api/questions", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: editingQuestion.id, category: editingQuestion.category, question: editingQuestion.question, }), }); if (response.ok) { const updated = await response.json(); setQuestions( questions.map((q) => (q.id === updated.id ? updated : q)) ); setEditingQuestion(null); } } catch (error) { console.error("Error updating question:", error); } }; const deleteQuestion = async (id: number) => { if (!confirm("Supprimer cette question ?")) return; try { const response = await fetch(`/api/questions?id=${id}`, { method: "DELETE", }); if (response.ok) { setQuestions(questions.filter((q) => q.id !== id)); } } catch (error) { console.error("Error deleting question:", error); } }; const moveQuestion = async (id: number, direction: "up" | "down") => { const modeQuestions = questions.filter((q) => q.mode === activeMode); const index = modeQuestions.findIndex((q) => q.id === id); if (direction === "up" && index === 0) return; if (direction === "down" && index === modeQuestions.length - 1) return; const swapIndex = direction === "up" ? index - 1 : index + 1; const currentQuestion = modeQuestions[index]; const swapQuestion = modeQuestions[swapIndex]; try { await fetch("/api/questions", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: currentQuestion.id, order_index: swapQuestion.order_index, }), }); await fetch("/api/questions", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: swapQuestion.id, order_index: currentQuestion.order_index, }), }); fetchQuestions(); } catch (error) { console.error("Error moving question:", error); } }; const filteredQuestions = questions.filter((q) => q.mode === activeMode); const categories = activeMode === "normal" ? NORMAL_CATEGORIES : CRISIS_CATEGORIES; const groupedQuestions = filteredQuestions.reduce((acc, q) => { if (!acc[q.category]) acc[q.category] = []; acc[q.category].push(q); return acc; }, {} as Record); if (loading) { return (
Chargement...
); } return (
← Retour

⚙️ Gestion des Questions

setIsAdding(true)} className="bg-blue-500 hover:bg-blue-600 px-6 py-3 rounded-xl transition-colors" > + Ajouter
{Object.entries(groupedQuestions).map( ([category, categoryQuestions]) => (

{category} ({categoryQuestions.length})

{categoryQuestions.map((q, idx) => (

{q.question}

))}
) )} {filteredQuestions.length === 0 && (

Aucune question pour ce mode

Clique sur "+ Ajouter" pour créer ta première question

)}
{isAdding && ( setIsAdding(false)} > e.stopPropagation()} className="bg-gray-800 rounded-2xl p-6 w-full max-w-lg" >

Nouvelle Question

Mode :

Catégorie :

{newQuestion.category === "__custom__" && ( setCustomCategory( e.target.value ) } placeholder="Nom de la nouvelle catégorie" className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none mt-2" /> )}

Question :