'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { dashboardApi } from '@/api/dashboardClient';
import AppNav from '@/components/liveclass/AppNav';
import LessonChecklist from '@/components/liveclass/course/LessonChecklist';
import LessonSidebar from '@/components/liveclass/course/LessonSidebar';

const BURGUNDY = '#4A1429';
const GOLD = '#D4B038';
const BORDER = '#E5DDD5';

const belongsTo = (row, user) => row && user && (
  String(row.user_id || '') === String(user.id || '')
  || String(row.user_email || '').toLowerCase() === String(user.email || '').toLowerCase()
  || String(row.created_by || '').toLowerCase() === String(user.email || '').toLowerCase()
);

function youtubeEmbedUrl(source) {
  const id = source?.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&?#/]+)/)?.[1];
  return id ? `https://www.youtube-nocookie.com/embed/${id}?rel=0&modestbranding=1&playsinline=1` : null;
}

export default function DashboardLessonClient({ lessonId }) {
  const [data, setData] = useState({ user: null, lesson: null, course: null, lessons: [], progressRows: [], enrollment: null });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const user = await dashboardApi.auth.me();
        const lesson = await dashboardApi.entities.Lesson.get(lessonId);
        const [course, lessons, progressRows, enrollments] = await Promise.all([
          dashboardApi.entities.Course.get(lesson.course_id),
          dashboardApi.entities.Lesson.filter({ course_id: lesson.course_id }),
          dashboardApi.entities.LessonProgress.filter({ course_id: lesson.course_id }),
          dashboardApi.entities.Enrollment.filter({ course_id: lesson.course_id }),
        ]);
        if (cancelled) return;
        setData({
          user, lesson, course,
          lessons: (lessons || []).sort((a, b) => (a.order || 0) - (b.order || 0)),
          progressRows: (progressRows || []).filter((row) => belongsTo(row, user)),
          enrollment: (enrollments || []).find((row) => belongsTo(row, user)) || null,
        });
      } catch (loadError) {
        if (loadError?.status === 401) { window.location.replace('/dashboard/login'); return; }
        setError(loadError?.message || 'Unable to load this lesson.');
      } finally { if (!cancelled) setLoading(false); }
    }
    load();
    return () => { cancelled = true; };
  }, [lessonId]);

  const progress = useMemo(() => data.progressRows.find((row) => String(row.lesson_id) === String(lessonId)) || null, [data.progressRows, lessonId]);
  const currentIndex = data.lessons.findIndex((lesson) => String(lesson.id) === String(lessonId));
  const previousLesson = currentIndex > 0 ? data.lessons[currentIndex - 1] : null;
  const nextLesson = currentIndex >= 0 && currentIndex < data.lessons.length - 1 ? data.lessons[currentIndex + 1] : null;
  const watchPct = progress?.is_completed ? 100 : Number(progress?.watch_percent || 0);

  const complete = async () => {
    if (!data.user || !data.lesson) return;
    setSaving(true);
    try {
      const payload = { user_id: data.user.id, user_email: data.user.email, lesson_id: data.lesson.id, course_id: data.lesson.course_id, is_completed: true, completed_at: new Date().toISOString(), progress_percent: 100, watch_percent: 100 };
      const saved = progress ? await dashboardApi.entities.LessonProgress.update(progress.id, payload) : await dashboardApi.entities.LessonProgress.create(payload);
      setData((current) => ({ ...current, progressRows: [...current.progressRows.filter((row) => String(row.lesson_id) !== String(data.lesson.id)), saved] }));
    } catch (saveError) { setError(saveError?.message || 'Unable to save progress.'); }
    finally { setSaving(false); }
  };

  if (loading) return <div className="min-h-screen bg-[#FAF5F0] pt-32 text-center font-bold">Loading lesson…</div>;

  const lesson = data.lesson;
  const videoSource = lesson?.video_url || lesson?.video_embed_url;
  const youtubeSource = youtubeEmbedUrl(videoSource);

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <AppNav />
      <main className="mx-auto max-w-[1440px] px-4 pb-16 pt-24 md:px-8">
        {error && <div className="mb-5 rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">{error}</div>}
        {lesson && <>
          <div className="mb-5 flex items-center justify-between">
            <Link href={`/dashboard/course/${data.course?.slug || lesson.course_id}`} className="text-sm font-black" style={{ color: BURGUNDY }}>← Back to {data.course?.title || 'course'}</Link>
            <span className="text-xs font-bold text-stone-500">Lesson {currentIndex + 1} of {data.lessons.length}</span>
          </div>

          <div className="grid grid-cols-1 gap-5 lg:grid-cols-4">
            <section className="space-y-5 lg:col-span-3">
              <div className="aspect-video overflow-hidden rounded-3xl bg-[#303030]">
                {youtubeSource ? <iframe title={lesson.title} src={youtubeSource} className="h-full w-full border-0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen /> : videoSource ? <video controls className="h-full w-full" src={videoSource} /> : <div className="flex h-full items-center justify-center text-sm font-bold text-white/60">Video unavailable</div>}
              </div>

              <article className="rounded-2xl border bg-white p-6 md:p-8" style={{ borderColor: BORDER }}>
                <p className="text-xs font-black uppercase tracking-widest" style={{ color: GOLD }}>Lesson {currentIndex + 1}</p>
                <h1 className="mt-2 text-2xl font-black md:text-3xl" style={{ color: BURGUNDY }}>{lesson.title}</h1>
                <div className="mt-5 whitespace-pre-wrap leading-7 text-stone-600">{lesson.content || lesson.description}</div>
                {lesson.resource_url && <a href={lesson.resource_url} target="_blank" rel="noreferrer" className="mt-6 inline-block font-black" style={{ color: BURGUNDY }}>Open lesson resource →</a>}
                <button onClick={complete} disabled={saving || progress?.is_completed} className="mt-8 block w-full rounded-xl px-6 py-4 text-sm font-black text-white disabled:bg-emerald-600" style={progress?.is_completed ? undefined : { backgroundColor: BURGUNDY }}>{progress?.is_completed ? '✓ Lesson completed' : saving ? 'Saving…' : 'Mark lesson complete'}</button>
              </article>

              <div className="flex items-center justify-between gap-4 pb-8 text-sm font-bold text-stone-500">
                {previousLesson ? <Link href={`/dashboard/lesson/${previousLesson.id}`} className="max-w-[42%] truncate">← {previousLesson.title}</Link> : <span />}
                {nextLesson ? <Link href={`/dashboard/lesson/${nextLesson.id}`} className="max-w-[42%] truncate text-right">{nextLesson.title} →</Link> : <span />}
              </div>
            </section>

            <aside className="hidden space-y-5 lg:block">
              <LessonChecklist hasQuiz={lesson.has_quiz} hasSubmission={lesson.has_submission} reflectionText={progress?.reflection_answer || ''} completed={Boolean(progress?.is_completed)} quizPassed={Boolean(progress?.quiz_passed)} watchPct={watchPct} />
              <LessonSidebar lessons={data.lessons} lessonId={lessonId} allLessonProgress={data.progressRows} enrollment={data.enrollment || { id: 'active' }} currentWatchPct={watchPct} maxHeight={580} />
            </aside>
          </div>
        </>}
      </main>
    </div>
  );
}
