import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import { LessonEditorForm } from "./LessonEditorForm";
import { parseLessonDescriptionMeta } from "@/lib/courses/lessonContent";

function getText(value: unknown): string {
  if (!value) return "";
  if (typeof value === "string") return value;
  if (typeof value === "object") {
    const text = value as Record<string, string>;
    return text.es || text.en || "";
  }
  return "";
}

interface PageProps {
    params: Promise<{ slug: string; lessonId: string }>;
}

export default async function LessonPage({ params }: PageProps) {
    const user = await requireTeacher();
    if (!user) redirect("/auth/login");

    const { slug, lessonId } = await params;

    // 1. Fetch Lesson + Course Info (for breadcrumbs)
    const lesson = await db.lesson.findUnique({
        where: { id: lessonId },
        include: {
            module: {
                include: {
                    course: {
                        select: { title: true, slug: true, authorId: true }
                    }
                }
            }
        }
    });

    // 2. Security & Null Checks
    if (!lesson) notFound();
    if (lesson.module.course.authorId !== user.id) redirect("/teacher");

    const lessonMeta = parseLessonDescriptionMeta(lesson.description);

    return (
        <div className="max-w-4xl mx-auto p-6">
            {/* Breadcrumbs */}
            <div className="flex items-center gap-2 text-sm text-slate-500 mb-6">
                <Link href="/teacher" className="hover:text-black">Cursos</Link>
                <span>/</span>
                <Link href={`/teacher/courses/${slug}/edit`} className="hover:text-black">
                    {getText(lesson.module.course.title)}
                </Link>
                <span>/</span>
                <span className="text-slate-900 font-medium">{getText(lesson.title)}</span>
            </div>

            <div className="flex items-center justify-between mb-8">
                <h1 className="text-3xl font-bold text-slate-900">Editar Lección</h1>
            </div>

            {/* The Client Form */}
            <LessonEditorForm
                lesson={{
                    ...lesson,
                    title: getText(lesson.title),
                    description: lessonMeta.text,
                    contentType: lessonMeta.contentType,
                    materialUrl: lessonMeta.materialUrl,
                    estimatedDurationMinutes: Math.max(0, Math.ceil((lesson.estimatedDuration ?? 0) / 60)),
                }}
                courseSlug={slug}
            />
        </div>
    );
}
