This commit is contained in:
Marcelo
2026-02-17 00:07:00 +00:00
parent b7a86a2d1c
commit be4ca2ed78
92 changed files with 6850 additions and 1188 deletions

45
components/teacher/TeacherDashboardClient.tsx Normal file → Executable file
View File

@@ -15,6 +15,13 @@ export default function TeacherDashboardClient() {
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, []);
const totalLessons = courses.reduce((sum, course) => sum + course.lessons.length, 0);
const totalStudents = courses.reduce((sum, course) => sum + course.students, 0);
const averageRating =
courses.length === 0 ? 0 : courses.reduce((sum, course) => sum + course.rating, 0) / courses.length;
const publishedCount = courses.filter((course) => course.status === "Published").length;
const draftCount = courses.filter((course) => course.status === "Draft").length;
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-3">
@@ -22,14 +29,39 @@ export default function TeacherDashboardClient() {
<h1 className="text-3xl font-bold text-slate-900">Teacher Dashboard</h1>
<p className="text-slate-600">Manage teacher-created courses stored locally for MVP.</p>
</div>
<Link
className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105"
href="/teacher/courses/new"
>
Create course
</Link>
<div className="flex gap-2">
<Link
className="rounded-md border border-slate-300 px-4 py-2 text-sm font-semibold hover:bg-slate-50"
href="/teacher/uploads"
>
Upload library
</Link>
<Link
className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105"
href="/teacher/courses/new"
>
Create course
</Link>
</div>
</div>
<section className="grid gap-4 sm:grid-cols-3">
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Courses</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{courses.length}</p>
<p className="mt-1 text-xs text-slate-500">Published: {publishedCount} | Draft: {draftCount}</p>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Lessons</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{totalLessons}</p>
</article>
<article className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Avg. rating</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">{averageRating.toFixed(1)}</p>
<p className="mt-1 text-xs text-slate-500">Students tracked: {totalStudents}</p>
</article>
</section>
{courses.length === 0 ? (
<div className="rounded-xl border border-dashed border-slate-300 bg-white p-6 text-sm text-slate-600">
No teacher-created courses yet.
@@ -41,6 +73,7 @@ export default function TeacherDashboardClient() {
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-brand">{course.level}</p>
<p className="mt-1 text-xs font-semibold uppercase tracking-wide text-slate-500">{course.status}</p>
<h2 className="text-xl font-semibold text-slate-900">{course.title}</h2>
<p className="mt-1 text-sm text-slate-600">{course.summary}</p>
</div>

493
components/teacher/TeacherEditCourseForm.tsx Normal file → Executable file
View File

@@ -1,176 +1,373 @@
// components/teacher/TeacherEditCourseForm.tsx
"use client";
import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
import {
updateCourse,
createModule,
createLesson,
reorderModules,
reorderLessons,
} from "@/app/(protected)/teacher/actions";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { getTeacherCourseBySlug, teacherCoursesUpdatedEventName, updateTeacherCourse } from "@/lib/data/teacherCourses";
import type { Course, CourseLevel } from "@/types/course";
import Link from "next/link";
import { toast } from "sonner";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"];
import { Prisma } from "@prisma/client";
type TeacherEditCourseFormProps = {
type CourseData = {
id: string;
slug: string;
title: Prisma.JsonValue;
description: Prisma.JsonValue;
level: string;
status: string;
price: number;
modules: {
id: string;
title: Prisma.JsonValue;
lessons: { id: string; title: Prisma.JsonValue }[];
}[];
};
export default function TeacherEditCourseForm({ slug }: TeacherEditCourseFormProps) {
export default function TeacherEditCourseForm({ course }: { course: CourseData }) {
const router = useRouter();
const [course, setCourse] = useState<Course | null>(null);
const [title, setTitle] = useState("");
const [level, setLevel] = useState<CourseLevel>("Beginner");
const [summary, setSummary] = useState("");
const [instructor, setInstructor] = useState("");
const [weeks, setWeeks] = useState(4);
const [rating, setRating] = useState(5);
const [saved, setSaved] = useState(false);
const [loading, setLoading] = useState(false);
const [optimisticModules, setOptimisticModules] = useState(course.modules);
useEffect(() => {
const load = () => {
const found = getTeacherCourseBySlug(slug) ?? null;
setCourse(found);
if (!found) return;
setTitle(found.title);
setLevel(found.level);
setSummary(found.summary);
setInstructor(found.instructor);
setWeeks(found.weeks);
setRating(found.rating);
};
setOptimisticModules(course.modules);
}, [course.modules]);
load();
window.addEventListener(teacherCoursesUpdatedEventName, load);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, [slug]);
const submit = (event: FormEvent) => {
event.preventDefault();
if (!course) return;
updateTeacherCourse(course.slug, {
title: title.trim(),
level,
summary: summary.trim(),
instructor: instructor.trim(),
weeks: Math.max(1, weeks),
rating: Math.min(5, Math.max(0, rating)),
});
setSaved(true);
window.setTimeout(() => setSaved(false), 1200);
// Helper for JSON/String fields
const getStr = (val: Prisma.JsonValue) => {
if (typeof val === "string") return val;
if (val && typeof val === "object" && !Array.isArray(val)) {
const v = val as Record<string, unknown>;
if (typeof v.en === "string") return v.en;
if (typeof v.es === "string") return v.es;
return "";
}
return "";
};
if (!course) {
return (
<div className="mx-auto max-w-2xl space-y-3 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900">Teacher course not found</h1>
<p className="text-slate-600">This editor only works for courses created in the teacher area.</p>
<Link className="inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/teacher">
Back to dashboard
</Link>
</div>
);
// 1. SAVE COURSE SETTINGS
async function handleSubmit(formData: FormData) {
setLoading(true);
const res = await updateCourse(course.id, course.slug, formData);
if (res.success) {
toast.success("Curso actualizado");
router.refresh();
} else {
toast.error("Error al guardar");
}
setLoading(false);
}
// 2. CREATE NEW MODULE
const handleAddModule = async () => {
setLoading(true); // Block UI while working
const res = await createModule(course.id);
if (res.success) {
toast.success("Módulo agregado");
router.refresh();
} else {
toast.error("Error al crear módulo");
}
setLoading(false);
};
// 3. CREATE NEW LESSON
const handleAddLesson = async (moduleId: string) => {
setLoading(true);
const res = await createLesson(moduleId);
if (res.success && res.lessonId) {
toast.success("Lección creada");
// Redirect immediately to the video upload page
router.push(`/teacher/courses/${course.slug}/lessons/${res.lessonId}`);
} else {
toast.error("Error al crear lección");
setLoading(false); // Only stop loading if we failed (otherwise we are redirecting)
}
};
// 4. REORDER MODULES (optimistic)
const handleReorderModule = async (moduleIndex: number, direction: "up" | "down") => {
const swapWith = direction === "up" ? moduleIndex - 1 : moduleIndex + 1;
if (swapWith < 0 || swapWith >= optimisticModules.length) return;
const next = [...optimisticModules];
[next[moduleIndex], next[swapWith]] = [next[swapWith], next[moduleIndex]];
setOptimisticModules(next);
const res = await reorderModules(optimisticModules[moduleIndex].id, direction);
if (res.success) {
router.refresh();
} else {
setOptimisticModules(course.modules);
toast.error(res.error ?? "Error al reordenar");
}
};
// 5. REORDER LESSONS (optimistic)
const handleReorderLesson = async (
moduleIndex: number,
lessonIndex: number,
direction: "up" | "down"
) => {
const lessons = optimisticModules[moduleIndex].lessons;
const swapWith = direction === "up" ? lessonIndex - 1 : lessonIndex + 1;
if (swapWith < 0 || swapWith >= lessons.length) return;
const nextModules = [...optimisticModules];
const nextLessons = [...lessons];
[nextLessons[lessonIndex], nextLessons[swapWith]] = [
nextLessons[swapWith],
nextLessons[lessonIndex],
];
nextModules[moduleIndex] = { ...nextModules[moduleIndex], lessons: nextLessons };
setOptimisticModules(nextModules);
const res = await reorderLessons(lessons[lessonIndex].id, direction);
if (res.success) {
router.refresh();
} else {
setOptimisticModules(course.modules);
toast.error(res.error ?? "Error al reordenar");
}
};
return (
<div className="mx-auto max-w-3xl space-y-5">
<form className="space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}>
<h1 className="text-2xl font-bold text-slate-900">Edit Course</h1>
<div className="mx-auto max-w-4xl space-y-6">
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Title</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Level</span>
<select
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setLevel(event.target.value as CourseLevel)}
value={level}
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-slate-900">Editar Curso</h1>
<div className="flex gap-2">
<Link
href={`/courses/${course.slug}`}
target="_blank"
className="px-3 py-2 text-sm border border-slate-300 rounded-md hover:bg-slate-50 flex items-center gap-2"
>
{levels.map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Summary</span>
<textarea
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setSummary(event.target.value)}
rows={3}
value={summary}
/>
</label>
<div className="grid gap-4 sm:grid-cols-2">
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Instructor</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setInstructor(event.target.value)}
value={instructor}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Weeks</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
min={1}
onChange={(event) => setWeeks(Number(event.target.value))}
type="number"
value={weeks}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Rating (0-5)</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
max={5}
min={0}
onChange={(event) => setRating(Number(event.target.value))}
step={0.1}
type="number"
value={rating}
/>
</label>
</div>
<div className="flex items-center gap-3">
<button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Save changes
</button>
{saved ? <span className="text-sm font-medium text-emerald-700">Saved</span> : null}
<span>👁</span> Ver Vista Previa
</Link>
<button
className="rounded-md border border-slate-300 px-4 py-2 text-sm hover:bg-slate-50"
onClick={() => router.push(`/teacher/courses/${course.slug}/lessons/new`)}
type="button"
form="edit-form"
type="submit"
disabled={loading}
className="bg-black text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-slate-800 disabled:opacity-50"
>
Add lesson
{loading ? "Guardando..." : "Guardar Cambios"}
</button>
</div>
</form>
</div>
<section className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h2 className="text-lg font-semibold text-slate-900">Lessons</h2>
<div className="mt-3 space-y-2">
{course.lessons.map((lesson) => (
<div key={lesson.id} className="rounded-md border border-slate-200 p-3 text-sm">
<p className="font-medium text-slate-900">{lesson.title}</p>
<p className="text-slate-600">
{lesson.type} | {lesson.minutes} min {lesson.isPreview ? "| Preview" : ""}
</p>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* LEFT COLUMN: Main Info */}
<div className="lg:col-span-2 space-y-6">
<form id="edit-form" action={handleSubmit} className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm space-y-4">
{/* Title */}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Título</label>
<input
name="title"
defaultValue={getStr(course.title)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black transition-all"
/>
</div>
))}
{/* Description */}
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Resumen</label>
<textarea
name="summary"
rows={4}
defaultValue={getStr(course.description)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black transition-all"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Nivel</label>
<select
name="level"
defaultValue={course.level}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
>
<option value="BEGINNER">Principiante</option>
<option value="INTERMEDIATE">Intermedio</option>
<option value="ADVANCED">Avanzado</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Estado</label>
<select
name="status"
defaultValue={course.status}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
>
<option value="DRAFT">Borrador</option>
<option value="PUBLISHED">Publicado</option>
</select>
</div>
</div>
</form>
{/* MODULES & LESSONS SECTION */}
<div className="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold">Plan de Estudios</h2>
<button
type="button"
onClick={handleAddModule}
disabled={loading}
className="text-sm text-blue-600 font-medium hover:underline disabled:opacity-50"
>
+ Nuevo Módulo
</button>
</div>
<div className="space-y-4">
{optimisticModules.length === 0 && (
<div className="text-center py-8 border border-dashed border-slate-200 rounded-lg bg-slate-50">
<p className="text-slate-500 text-sm mb-2">Tu curso está vacío.</p>
<button onClick={handleAddModule} className="text-black underline text-sm font-medium">
Agrega el primer módulo
</button>
</div>
)}
{optimisticModules.map((module, moduleIndex) => (
<div key={module.id} className="border border-slate-200 rounded-xl overflow-hidden bg-white shadow-sm">
{/* Module Header */}
<div className="bg-slate-50 px-4 py-2 border-b border-slate-200 flex justify-between items-center">
<div className="flex items-center gap-2">
<span className="font-medium text-sm text-slate-800">{getStr(module.title)}</span>
<div className="flex items-center">
<button
type="button"
onClick={() => handleReorderModule(moduleIndex, "up")}
disabled={moduleIndex === 0}
className="p-1.5 rounded-lg text-slate-500 hover:bg-slate-200 hover:text-slate-800 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover módulo arriba"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
</button>
<button
type="button"
onClick={() => handleReorderModule(moduleIndex, "down")}
disabled={moduleIndex === optimisticModules.length - 1}
className="p-1.5 rounded-lg text-slate-500 hover:bg-slate-200 hover:text-slate-800 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover módulo abajo"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
</div>
<button className="text-xs text-slate-500 hover:text-black">Editar Título</button>
</div>
{/* Lessons List */}
<div className="divide-y divide-slate-100">
{module.lessons.map((lesson, lessonIndex) => (
<div
key={lesson.id}
className="px-4 py-3 flex items-center gap-2 hover:bg-slate-50 transition-colors group"
>
<div className="flex flex-col">
<button
type="button"
onClick={() => handleReorderLesson(moduleIndex, lessonIndex, "up")}
disabled={lessonIndex === 0}
className="p-0.5 rounded text-slate-400 hover:bg-slate-200 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover lección arriba"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
</button>
<button
type="button"
onClick={() => handleReorderLesson(moduleIndex, lessonIndex, "down")}
disabled={lessonIndex === module.lessons.length - 1}
className="p-0.5 rounded text-slate-400 hover:bg-slate-200 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent transition-colors"
aria-label="Mover lección abajo"
>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
<Link
href={`/teacher/courses/${course.slug}/lessons/${lesson.id}`}
className="flex items-center gap-3 flex-1 min-w-0"
>
<span className="text-slate-400 text-lg group-hover:text-blue-500 flex-shrink-0"></span>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-slate-700 group-hover:text-slate-900">
{getStr(lesson.title)}
</p>
</div>
<span className="text-xs text-slate-400 opacity-0 group-hover:opacity-100 border border-slate-200 rounded px-2 py-1 flex-shrink-0">
Editar Contenido
</span>
</Link>
</div>
))}
{/* Add Lesson Button */}
<button
type="button"
onClick={() => handleAddLesson(module.id)}
disabled={loading}
className="w-full text-left px-4 py-3 text-xs text-slate-500 hover:text-blue-600 hover:bg-slate-50 font-medium flex items-center gap-2 transition-colors"
>
<span className="text-lg leading-none">+</span> Agregar Lección
</button>
</div>
</div>
))}
</div>
</div>
</div>
</section>
{/* RIGHT COLUMN: Price / Help */}
<div className="space-y-6">
<div className="bg-white p-4 rounded-xl border border-slate-200 shadow-sm">
<label className="block text-sm font-medium text-slate-700 mb-1">Precio (MXN)</label>
<input
form="edit-form"
name="price"
type="number"
step="0.01"
defaultValue={course.price}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
/>
<p className="mt-2 text-xs text-slate-500">
Si es 0, el curso será gratuito.
</p>
</div>
<div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
<h3 className="font-semibold text-slate-900 mb-2">💡 Tips</h3>
<ul className="text-sm text-slate-600 space-y-2 list-disc pl-4">
<li>Crea módulos para organizar tus temas.</li>
<li>Dentro de cada módulo, agrega lecciones.</li>
<li>Haz clic en una lección para <strong>subir el video</strong>.</li>
</ul>
</div>
</div>
</div>
</div>
);
}
}

178
components/teacher/TeacherNewCourseForm.tsx Normal file → Executable file
View File

@@ -1,112 +1,108 @@
"use client";
import { FormEvent, useState } from "react";
import { createCourse } from "@/app/(protected)/teacher/actions"; // Server Action
import { useRouter } from "next/navigation";
import { getAllCourseSlugs } from "@/lib/data/courseCatalog";
import { createTeacherCourse } from "@/lib/data/teacherCourses";
import type { CourseLevel } from "@/types/course";
const levels: CourseLevel[] = ["Beginner", "Intermediate", "Advanced"];
import { useState, FormEvent } from "react";
import Link from "next/link";
export default function TeacherNewCourseForm() {
const router = useRouter();
const [title, setTitle] = useState("");
const [level, setLevel] = useState<CourseLevel>("Beginner");
const [summary, setSummary] = useState("");
const [instructor, setInstructor] = useState("");
const [weeks, setWeeks] = useState(4);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = (event: FormEvent) => {
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setIsLoading(true);
setError(null);
const cleanTitle = title.trim();
const cleanSummary = summary.trim();
const cleanInstructor = instructor.trim();
const formData = new FormData(event.currentTarget);
if (!cleanTitle || !cleanSummary || !cleanInstructor) {
setError("Title, summary, and instructor are required.");
return;
try {
// 1. Call the Server Action
const result = await createCourse(formData);
if (result.success && result.data) {
// 2. Redirect to the Course Editor
// We will build the [slug]/edit page next
router.push(`/teacher/courses/${result.data.slug}/edit`);
} else {
setError(result.error || "Algo salió mal al crear el curso.");
setIsLoading(false);
}
} catch {
setError("Error de conexión. Inténtalo de nuevo.");
setIsLoading(false);
}
const created = createTeacherCourse(
{
title: cleanTitle,
level,
summary: cleanSummary,
instructor: cleanInstructor,
weeks: Math.max(1, weeks),
},
getAllCourseSlugs(),
);
router.push(`/teacher/courses/${created.slug}/edit`);
};
}
return (
<form className="mx-auto max-w-2xl space-y-4 rounded-xl border border-slate-200 bg-white p-6 shadow-sm" onSubmit={submit}>
<h1 className="text-2xl font-bold text-slate-900">Create Course</h1>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Title</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setTitle(event.target.value)}
value={title}
/>
</label>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Level</span>
<select
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setLevel(event.target.value as CourseLevel)}
value={level}
<div className="mx-auto max-w-2xl">
{/* Breadcrumb / Back Link */}
<div className="mb-6">
<Link
href="/teacher"
className="text-sm text-slate-500 hover:text-slate-900 transition-colors"
>
{levels.map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
</label>
Volver al Panel
</Link>
</div>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Summary</span>
<textarea
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setSummary(event.target.value)}
rows={3}
value={summary}
/>
</label>
<div className="rounded-xl border border-slate-200 bg-white p-8 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900 mb-2">Crear Nuevo Curso</h1>
<p className="text-slate-600 mb-8">
Empieza con un título. Podrás agregar lecciones, cuestionarios y más detalles en la siguiente pantalla.
</p>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Instructor</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
onChange={(event) => setInstructor(event.target.value)}
value={instructor}
/>
</label>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label
htmlFor="title"
className="block text-sm font-medium text-slate-700 mb-1"
>
Título del Curso
</label>
<input
id="title"
name="title"
type="text"
required
disabled={isLoading}
placeholder="Ej. Inglés Jurídico: Contratos Internacionales"
className="w-full rounded-lg border border-slate-300 px-4 py-2 outline-none focus:border-black focus:ring-1 focus:ring-black transition-all disabled:opacity-50 disabled:bg-slate-50"
autoFocus
/>
<p className="mt-2 text-xs text-slate-500">
Esto generará la URL pública de tu curso.
</p>
</div>
<label className="block">
<span className="mb-1 block text-sm text-slate-700">Weeks</span>
<input
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-brand"
min={1}
onChange={(event) => setWeeks(Number(event.target.value))}
type="number"
value={weeks}
/>
</label>
{error && (
<div className="bg-red-50 text-red-600 text-sm p-3 rounded-md border border-red-100">
{error}
</div>
)}
{error ? <p className="text-sm text-red-600">{error}</p> : null}
<button className="rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white hover:brightness-105" type="submit">
Create course
</button>
</form>
<div className="flex items-center gap-4 pt-4">
<Link
href="/teacher"
className="px-4 py-2 text-sm font-medium text-slate-600 hover:text-slate-900 transition-colors"
>
Cancelar
</Link>
<button
type="submit"
disabled={isLoading}
className="rounded-lg bg-black px-6 py-2 text-sm font-medium text-white hover:bg-slate-800 transition-colors disabled:opacity-50 flex items-center gap-2"
>
{isLoading ? (
<>Creating...</>
) : (
"Crear Curso & Continuar"
)}
</button>
</div>
</form>
</div>
</div>
);
}
}

0
components/teacher/TeacherNewLessonForm.tsx Normal file → Executable file
View File

View File

@@ -0,0 +1,140 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { getTeacherCourses, teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import type { Course } from "@/types/course";
type UploadAsset = {
id: string;
fileName: string;
type: "video" | "pdf" | "audio";
duration?: string;
size: string;
uploadedAt: string;
};
const mockAssets: UploadAsset[] = [
{ id: "asset-1", fileName: "contracts-intro-v1.mp4", type: "video", duration: "08:34", size: "48 MB", uploadedAt: "2026-02-01" },
{ id: "asset-2", fileName: "clause-red-flags.mp4", type: "video", duration: "12:12", size: "66 MB", uploadedAt: "2026-02-03" },
{ id: "asset-3", fileName: "brief-writing-reference.pdf", type: "pdf", size: "2.3 MB", uploadedAt: "2026-02-05" },
];
export default function TeacherUploadsLibraryClient() {
const [courses, setCourses] = useState<Course[]>([]);
const [selectedCourseByAsset, setSelectedCourseByAsset] = useState<Record<string, string>>({});
const [selectedLessonByAsset, setSelectedLessonByAsset] = useState<Record<string, string>>({});
const [message, setMessage] = useState<string | null>(null);
useEffect(() => {
const load = () => setCourses(getTeacherCourses());
load();
window.addEventListener(teacherCoursesUpdatedEventName, load);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, load);
}, []);
const lessonOptionsByCourse = useMemo(() => {
const map: Record<string, Array<{ id: string; title: string }>> = {};
for (const course of courses) {
map[course.slug] = course.lessons.map((lesson) => ({ id: lesson.id, title: lesson.title }));
}
return map;
}, [courses]);
const attachAsset = (assetId: string) => {
const courseSlug = selectedCourseByAsset[assetId];
const lessonId = selectedLessonByAsset[assetId];
if (!courseSlug || !lessonId) {
setMessage("Select a course and lesson before attaching.");
return;
}
setMessage(`Placeholder only: asset attached to ${courseSlug} / ${lessonId}.`);
};
return (
<div className="space-y-6">
<header className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<h1 className="text-3xl font-bold text-slate-900">Upload Library</h1>
<p className="mt-1 text-sm text-slate-600">Central cloud-style asset library for reusing videos and files across courses.</p>
<p className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
Upload disabled in MVP. This is a placeholder for backend integration.
</p>
<div className="mt-4 flex gap-2">
<Link className="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50" href="/teacher">
Back to dashboard
</Link>
<button className="rounded-md bg-slate-200 px-3 py-1.5 text-sm font-semibold text-slate-700" type="button">
Upload file (disabled)
</button>
</div>
</header>
{message ? (
<p className="rounded-md border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700">{message}</p>
) : null}
<section className="grid gap-4">
{mockAssets.map((asset) => {
const selectedCourse = selectedCourseByAsset[asset.id] ?? "";
const lessonOptions = selectedCourse ? lessonOptionsByCourse[selectedCourse] ?? [] : [];
return (
<article key={asset.id} className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-brand">{asset.type}</p>
<h2 className="text-lg font-semibold text-slate-900">{asset.fileName}</h2>
<p className="mt-1 text-sm text-slate-600">
{asset.size} {asset.duration ? `| ${asset.duration}` : ""} | Uploaded {asset.uploadedAt}
</p>
</div>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
<select
className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
onChange={(event) => {
const slug = event.target.value;
setSelectedCourseByAsset((current) => ({ ...current, [asset.id]: slug }));
setSelectedLessonByAsset((current) => ({ ...current, [asset.id]: "" }));
}}
value={selectedCourse}
>
<option value="">Select course</option>
{courses.map((course) => (
<option key={course.slug} value={course.slug}>
{course.title}
</option>
))}
</select>
<select
className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
disabled={!selectedCourse}
onChange={(event) =>
setSelectedLessonByAsset((current) => ({ ...current, [asset.id]: event.target.value }))
}
value={selectedLessonByAsset[asset.id] ?? ""}
>
<option value="">Select lesson</option>
{lessonOptions.map((lesson) => (
<option key={lesson.id} value={lesson.id}>
{lesson.title}
</option>
))}
</select>
<button
className="rounded-md border border-slate-300 px-3 py-2 text-sm font-semibold hover:bg-slate-50"
onClick={() => attachAsset(asset.id)}
type="button"
>
Attach to lesson
</button>
</div>
</article>
);
})}
</section>
</div>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import { useState } from "react";
import { createBrowserClient } from "@supabase/ssr";
import { toast } from "sonner"; // or use alert()
interface VideoUploadProps {
lessonId: string;
currentVideoUrl?: string | null;
onUploadComplete: (url: string) => void; // Callback to save to DB
}
export default function VideoUpload({ lessonId, currentVideoUrl, onUploadComplete }: VideoUploadProps) {
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
setProgress(0);
const supabase = createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
// Create a unique file path: lesson_id/timestamp_filename
const filePath = `${lessonId}/${Date.now()}_${file.name}`;
const { error } = await supabase.storage
.from("courses") // Make sure this bucket exists!
.upload(filePath, file, {
upsert: true,
});
if (error) {
toast.error("Upload failed: " + error.message);
setUploading(false);
return;
}
// Get Public URL
const { data: { publicUrl } } = supabase.storage
.from("courses")
.getPublicUrl(filePath);
onUploadComplete(publicUrl);
setUploading(false);
};
return (
<div className="border border-slate-200 rounded-lg p-6 bg-slate-50">
<h3 className="font-medium text-slate-900 mb-2">Video de la Lección</h3>
{currentVideoUrl ? (
<div className="mb-4 aspect-video bg-black rounded-md overflow-hidden relative group">
<video src={currentVideoUrl} controls className="w-full h-full" />
<div className="absolute inset-0 bg-black/50 hidden group-hover:flex items-center justify-center">
<p className="text-white text-sm">Subir otro para reemplazar</p>
</div>
</div>
) : (
<div className="mb-4 aspect-video bg-slate-200 rounded-md flex items-center justify-center text-slate-400">
Sin video
</div>
)}
<div className="flex flex-col gap-2">
<label className="block w-full">
<span className="sr-only">Choose video</span>
<input
type="file"
accept="video/*"
onChange={handleUpload}
disabled={uploading}
className="block w-full text-sm text-slate-500
file:mr-4 file:py-2 file:px-4
file:rounded-full file:border-0
file:text-sm file:font-semibold
file:bg-black file:text-white
hover:file:bg-slate-800
"
/>
</label>
{uploading && (
<div className="w-full bg-slate-200 rounded-full h-2 mt-2">
<div className="bg-black h-2 rounded-full transition-all" style={{ width: `${progress}%` }}></div>
</div>
)}
</div>
</div>
);
}