import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import Link from "next/link";
import { PlayCircle, CheckCircle2, Circle, ArrowLeft, Menu } from "lucide-react";

export const metadata = {
  title: "Learning Player - RIMA Academy",
  description: "Learn and progress through your course.",
};

export default async function LearnPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ lessonId?: string }>;
}) {
  const { id } = await params;
  const { lessonId } = await searchParams;
  
  const session = await auth();
  if (!session?.user?.id) {
    redirect("/login?callbackUrl=" + encodeURIComponent(`/courses/${id}/learn`));
  }
  
  const userId = session.user.id;

  // Verify enrollment
  const enrollment = await db.enrollment.findUnique({
    where: {
      userId_courseId: {
        userId: userId,
        courseId: id,
      }
    }
  });

  if (!enrollment || enrollment.status !== "ACTIVE") {
    redirect(`/courses/${id}`);
  }

  // Fetch Course details with Curriculum
  const course = await db.course.findUnique({
    where: { id },
    include: {
      modules: {
        orderBy: { orderIndex: "asc" },
        include: {
          lessons: {
            orderBy: { orderIndex: "asc" },
            include: {
              progress: {
                where: { userId: userId }
              }
            }
          }
        }
      }
    }
  });

  if (!course) redirect("/dashboard");

  // Determine current lesson
  let currentLesson = null;
  let activeModuleId = null;

  // Flatten lessons for easy navigation
  const allLessons = course.modules.flatMap(m => m.lessons);
  
  if (allLessons.length > 0) {
    if (lessonId) {
      currentLesson = allLessons.find(l => l.id === lessonId) || allLessons[0];
    } else {
      // Find first uncompleted lesson
      currentLesson = allLessons.find(l => !l.progress[0]?.isCompleted) || allLessons[0];
    }
    activeModuleId = currentLesson.moduleId;
  }

  const currentIndex = allLessons.findIndex(l => l.id === currentLesson?.id);
  const prevLesson = currentIndex > 0 ? allLessons[currentIndex - 1] : null;
  const nextLesson = currentIndex < allLessons.length - 1 ? allLessons[currentIndex + 1] : null;

  // Calculate Progress
  const completedLessons = allLessons.filter(l => l.progress[0]?.isCompleted).length;
  const progressPercent = allLessons.length > 0 ? Math.round((completedLessons / allLessons.length) * 100) : 0;

  return (
    <div className="flex h-screen bg-rima-background overflow-hidden font-sans">
      
      {/* SIDEBAR (Desktop) */}
      <aside className="hidden lg:flex w-80 flex-col bg-rima-surface/30 border-r border-rima-border/50 backdrop-blur-xl h-full relative z-20">
        <div className="p-6 border-b border-rima-border/50">
          <Link href="/dashboard" className="inline-flex items-center text-sm font-semibold text-rima-muted hover:text-rima-text transition-colors mb-6">
            <ArrowLeft className="w-4 h-4 mr-2" />
            Înapoi la Dashboard
          </Link>
          <h2 className="text-xl font-bold text-white mb-4 font-heading">{course.title}</h2>
          
          {/* Progress Bar */}
          <div className="space-y-2">
            <div className="flex justify-between text-xs font-semibold text-rima-muted uppercase tracking-wider">
              <span>Progres</span>
              <span className={progressPercent === 100 ? "text-rima-success" : "text-rima-text"}>{progressPercent}%</span>
            </div>
            <div className="h-1.5 w-full bg-rima-border/50 rounded-full overflow-hidden">
              <div 
                className="h-full bg-rima-primary rounded-full transition-all duration-1000 ease-out"
                style={{ width: `${progressPercent}%` }}
              />
            </div>
          </div>
        </div>

        {/* Modules List */}
        <div className="flex-1 overflow-y-auto scrollbar-thin">
          {course.modules.length === 0 ? (
            <div className="p-6 text-sm text-rima-muted text-center">Niciun modul disponibil momentan.</div>
          ) : (
            <div className="py-2">
              {course.modules.map((mod, modIdx) => (
                <div key={mod.id} className="mb-2">
                  <div className="px-6 py-3 text-xs font-bold text-rima-muted uppercase tracking-widest sticky top-0 bg-rima-surface/90 backdrop-blur-md border-y border-white/5 z-10">
                    Modulul {modIdx + 1}: {mod.title}
                  </div>
                  <div className="flex flex-col py-2">
                    {mod.lessons.map((lesson, lessIdx) => {
                      const isActive = currentLesson?.id === lesson.id;
                      const isCompleted = lesson.progress[0]?.isCompleted;
                      
                      return (
                        <Link
                          key={lesson.id}
                          href={`/courses/${course.id}/learn?lessonId=${lesson.id}`}
                          className={`flex items-start gap-3 px-6 py-3 transition-colors ${
                            isActive 
                              ? "bg-rima-primary/10 border-l-2 border-rima-primary" 
                              : "border-l-2 border-transparent hover:bg-white/5"
                          }`}
                        >
                          <div className="mt-0.5 shrink-0">
                            {isCompleted ? (
                              <CheckCircle2 className="w-4 h-4 text-rima-success" />
                            ) : isActive ? (
                              <PlayCircle className="w-4 h-4 text-rima-primary" />
                            ) : (
                              <Circle className="w-4 h-4 text-rima-muted" />
                            )}
                          </div>
                          <div>
                            <span className={`text-sm font-medium ${isActive ? "text-white" : "text-rima-text"}`}>
                              {lessIdx + 1}. {lesson.title}
                            </span>
                            <div className="text-xs text-rima-muted mt-1 flex items-center gap-2">
                              {lesson.minimumTimeSecs > 0 && (
                                <span>{Math.round(lesson.minimumTimeSecs / 60)} min</span>
                              )}
                              {lesson.requireQuiz && (
                                <span className="bg-white/10 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold text-rima-accent">Quiz inclus</span>
                              )}
                            </div>
                          </div>
                        </Link>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </aside>

      {/* MAIN CONTENT */}
      <main className="flex-1 flex flex-col h-full relative overflow-y-auto">
        <div className="absolute top-0 right-1/4 w-96 h-96 bg-rima-primary/10 rounded-full blur-[120px] pointer-events-none -z-10" />
        
        {/* Mobile Header */}
        <div className="lg:hidden flex items-center p-4 border-b border-rima-border/50 bg-rima-surface/80 backdrop-blur-xl sticky top-0 z-30">
          <Link href="/dashboard" className="p-2 text-rima-muted hover:text-white mr-2">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <div className="flex-1 truncate font-bold text-sm text-white font-heading">{course.title}</div>
          <button className="p-2 text-rima-muted hover:text-white">
            <Menu className="w-5 h-5" />
          </button>
        </div>

        {currentLesson ? (
          <div className="w-full max-w-5xl mx-auto p-4 lg:p-10 pb-24">
            <div className="mb-6 flex items-center gap-3">
              <span className="inline-flex items-center rounded-full bg-rima-primary/10 border border-rima-primary/20 px-3 py-1 text-xs font-bold uppercase tracking-wider text-rima-primary">
                Lecția Curentă
              </span>
              {currentLesson.progress[0]?.isCompleted && (
                <span className="inline-flex items-center rounded-full bg-rima-success/10 border border-rima-success/20 px-3 py-1 text-xs font-bold uppercase tracking-wider text-rima-success">
                  Finalizat
                </span>
              )}
            </div>
            
            <h1 className="text-3xl lg:text-4xl font-bold text-white mb-8 font-heading">{currentLesson.title}</h1>
            
            {/* Video Player Area */}
            <div className="w-full aspect-video bg-black rounded-2xl overflow-hidden shadow-2xl border border-white/5 mb-8 relative group">
              {currentLesson.videoUrl ? (
                // Assuming it's an iframe embed for MVP. In prod use a real player component.
                <iframe 
                  src={currentLesson.videoUrl.includes('youtube') 
                    ? currentLesson.videoUrl.replace('watch?v=', 'embed/') 
                    : currentLesson.videoUrl} 
                  className="w-full h-full"
                  allowFullScreen
                  title={currentLesson.title}
                />
              ) : (
                <div className="absolute inset-0 flex flex-col items-center justify-center text-rima-muted p-6 text-center bg-rima-surface/50">
                  <PlayCircle className="w-16 h-16 mb-4 opacity-50" />
                  <p className="text-lg font-medium text-white">Niciun material video atașat</p>
                  <p className="text-sm mt-2">Această lecție se bazează pe textul de mai jos.</p>
                </div>
              )}
            </div>

            {/* Navigation Buttons */}
            <div className="flex flex-col sm:flex-row items-center justify-between gap-4 mb-12 border-b border-rima-border/50 pb-8">
              {prevLesson ? (
                <Link href={`/courses/${course.id}/learn?lessonId=${prevLesson.id}`} className="w-full sm:w-auto px-6 py-3 rounded-xl bg-rima-surface text-white font-semibold text-sm hover:bg-white/10 transition-colors border border-white/5 text-center">
                  ← Lecția Anterioară
                </Link>
              ) : <div className="w-full sm:w-auto hidden sm:block"></div>}
              
              <form action={async () => {
                'use server';
                // Server action to mark as complete
                if (!session?.user?.id) return;
                await db.lessonProgress.upsert({
                  where: {
                    userId_lessonId: { userId: session.user.id, lessonId: currentLesson!.id }
                  },
                  update: { isCompleted: true, completedAt: new Date() },
                  create: { userId: session.user.id, lessonId: currentLesson!.id, isCompleted: true, completedAt: new Date() }
                });
                // Redirect logic depends if there is next lesson
              }}>
                <button type="submit" className="w-full sm:w-auto px-8 py-3 rounded-xl bg-rima-primary text-white font-bold text-sm uppercase tracking-wider hover:opacity-90 transition-opacity shadow-[0_0_20px_rgba(59,130,246,0.3)]">
                  Marchează ca Finalizat
                </button>
              </form>

              {nextLesson ? (
                <Link href={`/courses/${course.id}/learn?lessonId=${nextLesson.id}`} className="w-full sm:w-auto px-6 py-3 rounded-xl bg-rima-surface text-white font-semibold text-sm hover:bg-white/10 transition-colors border border-white/5 text-center">
                  Următoarea Lecție →
                </Link>
              ) : <div className="w-full sm:w-auto hidden sm:block"></div>}
            </div>

            {/* Lesson Content Area */}
            <div className="prose prose-invert max-w-none text-rima-text prose-p:leading-relaxed prose-headings:font-heading">
              {currentLesson.content ? (
                <div dangerouslySetInnerHTML={{ __html: currentLesson.content }} />
              ) : (
                <p className="italic text-rima-muted">Conținutul text nu a fost adăugat pentru această lecție.</p>
              )}
            </div>

          </div>
        ) : (
          <div className="flex-1 flex flex-col items-center justify-center p-8 text-center">
            <h2 className="text-2xl font-bold text-white mb-4">Conținut Indisponibil</h2>
            <p className="text-rima-muted max-w-md">Acest curs nu are lecții adăugate momentan. Te rugăm să verifici mai târziu sau să contactezi suportul.</p>
            <Link href="/dashboard" className="mt-8 px-6 py-3 rounded-xl bg-rima-primary text-white font-bold">
              Întoarce-te la Dashboard
            </Link>
          </div>
        )}
      </main>
    </div>
  );
}
