// modules/admin/components/courses/CreateLessonDialog.jsx // Lightweight "create a brand-new lesson and attach it to this unit" dialog — // the create-new counterpart to AttachLessonsDialog's attach-existing flow. import { useEffect } from "react"; import { useForm, useFieldArray } from "react-hook-form"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { Plus, Trash2 } from "lucide-react"; import { useCourses } from "@/contexts/AdminCoursesContext"; import { useAuth } from "@/contexts/AuthContext"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Spinner } from "@/components/ui/spinner"; const schema = z.object({ title: z.string().min(1, "Title is required."), description: z.string().optional(), order: z.coerce.number().min(0).default(0), objectives: z.array(z.object({ value: z.string().min(1, "Objective cannot be empty.") })).default([]), }); export default function CreateLessonDialog({ open, onOpenChange, courseId, unitId, nextOrder = 0, onCreated, draftMode = false }) { const { createLesson, loading } = useCourses(); const { user } = useAuth(); const { register, handleSubmit, reset, control, formState: { errors } } = useForm({ resolver: zodResolver(schema), defaultValues: { title: "", description: "", order: nextOrder, objectives: [] }, }); const { fields, append, remove } = useFieldArray({ control, name: "objectives" }); useEffect(() => { if (open) reset({ title: "", description: "", order: nextOrder, objectives: [] }); }, [open, nextOrder, reset]); const onValid = async (values) => { const objectives = values.objectives.map((o) => o.value); if (draftMode) { onCreated?.({ lesson_id: null, key: crypto.randomUUID(), title: values.title, description: values.description, order_index: values.order, objectives, }); onOpenChange(false); return; } const result = await createLesson(courseId, unitId, { ...values, objectives, createdBy: user?.user_id, }); const lesson = result?.data?.data ?? null; if (!lesson) return; onCreated?.(lesson); onOpenChange(false); }; return ( New Lesson
{errors.title &&

{errors.title.message}

}