"use client"; import { useEffect, useState } from "react"; import { cmsApi, Course, Organization } from "@/lib/api"; import Link from "next/link"; import { useAuth } from "@/context/AuthContext"; import { useTranslation } from "@/context/I18nContext"; import { Plus, BookOpen, Download, Upload, Sparkles, Wand2, Trash2 } from "lucide-react"; import OrganizationSelector from "@/components/OrganizationSelector"; import Modal from "@/components/Modal"; import PageLayout from "@/components/PageLayout"; export default function StudioDashboard() { const { t } = useTranslation(); const [courses, setCourses] = useState([]); const [loading, setLoading] = useState(true); const { user } = useAuth(); useEffect(() => { const loadCourses = async () => { if (!user) { setLoading(false); return; }; try { const data = await cmsApi.getCourses(); setCourses(data); } catch (err) { console.error("Failed to load courses", err); } finally { setLoading(false); } }; loadCourses(); }, [user]); const [organizations, setOrganizations] = useState([]); const [isOrgModalOpen, setIsOrgModalOpen] = useState(false); const [isTitleModalOpen, setIsTitleModalOpen] = useState(false); const [isAIModalOpen, setIsAIModalOpen] = useState(false); const [newCourseTitle, setNewCourseTitle] = useState(""); const [aiPrompt, setAiPrompt] = useState(""); const [isGenerating, setIsGenerating] = useState(false); useEffect(() => { const loadOrgs = async () => { if (user?.role === 'admin' && user?.organization_id === '00000000-0000-0000-0000-000000000001') { try { const orgs = await cmsApi.getOrganizations(); setOrganizations(orgs); } catch (err) { console.error("Failed to load organizations", err); } } }; loadOrgs(); }, [user]); const handleCreateCourse = async () => { setIsTitleModalOpen(true); }; const onTitleConfirm = (e: React.FormEvent) => { e.preventDefault(); if (!newCourseTitle) return; setIsTitleModalOpen(false); const isSuperAdmin = user?.role === 'admin' && user?.organization_id === '00000000-0000-0000-0000-000000000001'; if (isSuperAdmin && organizations.length > 0) { setIsOrgModalOpen(true); } else { createCourse(); } }; const createCourse = async (targetOrgId?: string) => { try { const newCourse = await cmsApi.createCourse(newCourseTitle, targetOrgId); setCourses((prev: Course[]) => [...prev, newCourse]); setNewCourseTitle(""); } catch (err) { console.error("Failed to create course", err); alert("Failed to create course. Please ensure the backend is running."); } }; const handleAIGenerate = async (e: React.FormEvent) => { e.preventDefault(); if (!aiPrompt) return; setIsGenerating(true); try { const newCourse = await cmsApi.generateCourse(aiPrompt); setCourses((prev: Course[]) => [...prev, newCourse]); setAiPrompt(""); setIsAIModalOpen(false); alert("Course generated successfully with AI!"); } catch (err) { console.error("AI generation failed", err); alert("Failed to generate course with AI. Check backend logs and AI provider status."); } finally { setIsGenerating(false); } }; const handleExport = async (e: React.MouseEvent, courseId: string, title: string) => { e.preventDefault(); e.stopPropagation(); try { const data = await cmsApi.exportCourse(courseId); const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `course_${title.replace(/\s+/g, '_')}.json`; document.body.appendChild(link); link.click(); document.body.removeChild(link); } catch (err) { console.error("Export failed", err); alert("Failed to export course"); } }; const handleImport = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = async (event) => { try { const json = JSON.parse(event.target?.result as string); const newCourse = await cmsApi.importCourse(json); setCourses((prev: Course[]) => [...prev, newCourse]); alert("Course imported successfully!"); } catch (err) { console.error("Import failed", err); alert("Failed to import course. Ensure the file is a valid OpenCCB course export."); } }; reader.readAsText(file); }; const handleDeleteCourse = async (e: React.MouseEvent, courseId: string, title: string) => { e.preventDefault(); e.stopPropagation(); if (!confirm(t('confirm_delete_course') || `Are you sure you want to delete "${title}"? This action cannot be undone.`)) { return; } try { await cmsApi.deleteCourse(courseId); setCourses(prev => prev.filter(c => c.id !== courseId)); } catch (err) { console.error("Delete failed", err); alert("Failed to delete course"); } }; return ( } > {loading ? (
{[1, 2, 3].map(i => (
))}
) : courses.length === 0 ? (

Aún no has creado ningún curso.

) : (
{courses.map((course: Course) => (

{course.title}

{course.description || "Sin descripción disponible."}

Última actualización: {new Date(course.updated_at).toLocaleDateString()} ID: {course.id.slice(0, 4)}...
))}
)} {/* New Course Title Modal */} setIsTitleModalOpen(false)} title="Create New Course" >
setNewCourseTitle(e.target.value)} placeholder="e.g. Advanced Rust Development" className="w-full bg-black/5 dark:bg-black/40 border border-black/10 dark:border-white/10 rounded-lg px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all text-gray-900 dark:text-white" />
{/* AI Wizard Modal */} !isGenerating && setIsAIModalOpen(false)} title="AI Course Wizard" >

Describe the course topic and target audience. Our AI will structure the modules and lessons for you in seconds.