<template>
	<div v-if="lesson.data" class="">
		<header
			class="sticky top-0 z-10 flex items-center justify-between border-b bg-white px-3 py-2.5 sm:px-5"
		>
			<Breadcrumbs class="h-7" :items="breadcrumbs" />
		</header>
		<div class="grid md:grid-cols-[70%,30%] h-full">
			<div
				v-if="lesson.data.no_preview"
				class="border-r-2 text-center pt-10 px-5 md:px-0 pb-10"
			>
				<p class="mb-4">
					{{
						__(
							'This lesson is not available for preview. Please enroll in the course to access it.'
						)
					}}
				</p>
				<router-link
					:to="{ name: 'CourseDetail', params: { courseName: courseName } }"
				>
					<Button variant="solid">
						{{ __('Start Learning') }}
					</Button>
				</router-link>
			</div>
			<div v-else class="border-r-2 container pt-5 pb-10 px-5">
				<div class="flex flex-col md:flex-row md:items-center justify-between">
					<div class="text-3xl font-semibold">
						{{ lesson.data.title }}
					</div>
					<div class="flex items-center mt-2 md:mt-0">
						<router-link
							v-if="lesson.data.prev"
							:to="{
								name: 'Lesson',
								params: {
									courseName: courseName,
									chapterNumber: lesson.data.prev.split('.')[0],
									lessonNumber: lesson.data.prev.split('.')[1],
								},
							}"
						>
							<Button class="mr-2">
								<template #prefix>
									<ChevronLeft class="w-4 h-4 stroke-1" />
								</template>
								<span>
									{{ __('Previous') }}
								</span>
							</Button>
						</router-link>
						<router-link
							v-if="allowEdit()"
							:to="{
								name: 'CreateLesson',
								params: {
									courseName: courseName,
									chapterNumber: props.chapterNumber,
									lessonNumber: props.lessonNumber,
								},
							}"
						>
							<Button class="mr-2">
								{{ __('Edit') }}
							</Button>
						</router-link>
						<router-link
							v-if="lesson.data.next"
							:to="{
								name: 'Lesson',
								params: {
									courseName: courseName,
									chapterNumber: lesson.data.next.split('.')[0],
									lessonNumber: lesson.data.next.split('.')[1],
								},
							}"
						>
							<Button>
								<template #suffix>
									<ChevronRight class="w-4 h-4 stroke-1" />
								</template>
								<span>
									{{ __('Next') }}
								</span>
							</Button>
						</router-link>
					</div>
				</div>

				<div class="flex items-center mt-2">
					<span
						class="mr-1"
						:class="{
							'avatar-group overlap': lesson.data.instructors.length > 1,
						}"
					>
						<UserAvatar
							v-for="instructor in lesson.data.instructors"
							:user="instructor"
						/>
					</span>
					<span v-if="lesson.data.instructors.length == 1">
						{{ lesson.data.instructors[0].full_name }}
					</span>
					<span v-if="lesson.data.instructors.length == 2">
						{{ lesson.data.instructors[0].first_name }} and
						{{ lesson.data.instructors[1].first_name }}
					</span>
					<span v-if="lesson.data.instructors.length > 2">
						{{ lesson.data.instructors[0].first_name }} and
						{{ lesson.data.instructors.length - 1 }} others
					</span>
				</div>
				<div
					v-if="lesson.data.instructor_content && allowInstructorContent()"
					class="bg-gray-100 p-3 rounded-md mt-6"
				>
					<div class="text-gray-600 font-medium">
						{{ __('Instructor Notes') }}
					</div>
					<div
						id="instructor-content"
						class="ProseMirror prose prose-table:table-fixed prose-td:p-2 prose-th:p-2 prose-td:border prose-th:border prose-td:border-gray-300 prose-th:border-gray-300 prose-td:relative prose-th:relative prose-th:bg-gray-100 prose-sm max-w-none !whitespace-normal"
					></div>
				</div>
				<div
					v-else-if="lesson.data.instructor_notes"
					class="ProseMirror prose prose-table:table-fixed prose-td:p-2 prose-th:p-2 prose-td:border prose-th:border prose-td:border-gray-300 prose-th:border-gray-300 prose-td:relative prose-th:relative prose-th:bg-gray-100 prose-sm max-w-none !whitespace-normal mt-6"
				>
					<LessonContent :content="lesson.data.instructor_notes" />
				</div>
				<div
					v-if="lesson.data.content"
					class="ProseMirror prose prose-table:table-fixed prose-td:p-2 prose-th:p-2 prose-td:border prose-th:border prose-td:border-gray-300 prose-th:border-gray-300 prose-td:relative prose-th:relative prose-th:bg-gray-100 prose-sm max-w-none !whitespace-normal mt-5"
				>
					<div id="editor"></div>
				</div>
				<div
					v-else
					class="ProseMirror prose prose-table:table-fixed prose-td:p-2 prose-th:p-2 prose-td:border prose-th:border prose-td:border-gray-300 prose-th:border-gray-300 prose-td:relative prose-th:relative prose-th:bg-gray-100 prose-sm max-w-none !whitespace-normal mt-5"
				>
					<LessonContent
						:content="lesson.data.body"
						:youtube="lesson.data.youtube"
						:quizId="lesson.data.quiz_id"
					/>
				</div>
				<div class="mt-20">
					<Discussions
						v-if="allowDiscussions()"
						:title="'Questions'"
						:doctype="'Course Lesson'"
						:docname="lesson.data.name"
						:key="lesson.data.name"
					/>
				</div>
			</div>
			<div class="sticky top-10">
				<div class="bg-gray-50 p-5 border-b-2">
					<div class="text-lg font-semibold">
						{{ lesson.data.course_title }}
					</div>
					<div v-if="user && lesson.data.membership" class="text-sm mt-3">
						{{ Math.ceil(lesson.data.membership.progress) }}% completed
					</div>
					<div
						v-if="user && lesson.data.membership"
						class="w-full bg-gray-200 rounded-full h-1 my-2"
					>
						<div
							class="bg-gray-900 h-1 rounded-full"
							:style="{
								width: Math.ceil(lesson.data.membership.progress) + '%',
							}"
						></div>
					</div>
				</div>
				<CourseOutline :courseName="courseName" :key="chapterNumber" />
			</div>
		</div>
	</div>
</template>
<script setup>
import { createResource, Breadcrumbs, Button } from 'frappe-ui'
import { computed, watch, ref, inject, createApp } from 'vue'
import CourseOutline from '@/components/CourseOutline.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import { useRoute } from 'vue-router'
import { ChevronLeft, ChevronRight } from 'lucide-vue-next'
import Discussions from '@/components/Discussions.vue'
import { getEditorTools } from '../utils'
import EditorJS from '@editorjs/editorjs'
import LessonContent from '@/components/LessonContent.vue'

const user = inject('$user')
const route = useRoute()
let editor, instructorEditor

const props = defineProps({
	courseName: {
		type: String,
		required: true,
	},
	chapterNumber: {
		type: String,
		required: true,
	},
	lessonNumber: {
		type: String,
		required: true,
	},
})

const lesson = createResource({
	url: 'lms.lms.utils.get_lesson',
	cache: ['lesson', props.courseName, props.chapterNumber, props.lessonNumber],
	makeParams(values) {
		return {
			course: props.courseName,
			chapter: values ? values.chapter : props.chapterNumber,
			lesson: values ? values.lesson : props.lessonNumber,
		}
	},
	auto: true,
	onSuccess(data) {
		if (data.membership)
			current_lesson.submit({
				name: data.membership.name,
				lesson_name: data.name,
			})
		if (data.content) editor = renderEditor('editor', data.content)

		if (data.instructor_content)
			instructorEditor = renderEditor(
				'instructor-content',
				data.instructor_content
			)

		markProgress(data)
	},
})

const renderEditor = (holder, content) => {
	return new EditorJS({
		holder: holder,
		tools: getEditorTools(),
		data: JSON.parse(content),
		readOnly: true,
		defaultBlock: 'embed', // editor adds an empty block at the top, so to avoid that added default block as embed
	})
}

const markProgress = (data) => {
	setTimeout(() => {
		if (!data.progress) progress.submit()
	}, 60000)
}

const current_lesson = createResource({
	url: 'frappe.client.set_value',
	makeParams(values) {
		return {
			doctype: 'LMS Enrollment',
			name: values.name,
			fieldname: 'current_lesson',
			value: values.lesson_name,
		}
	},
})

const progress = createResource({
	url: 'lms.lms.doctype.course_lesson.course_lesson.save_progress',
	makeParams() {
		return {
			lesson: lesson.data.name,
			course: props.courseName,
		}
	},
})

const breadcrumbs = computed(() => {
	let items = [{ label: 'All Courses', route: { name: 'Courses' } }]
	items.push({
		label: lesson?.data?.course_title,
		route: { name: 'CourseDetail', params: { course: props.courseName } },
	})
	items.push({
		label: lesson?.data?.title,
		route: {
			name: 'Lesson',
			params: {
				course: props.courseName,
				chapterNumber: props.chapterNumber,
				lessonNumber: props.lessonNumber,
			},
		},
	})
	return items
})

watch(
	[() => route.params.chapterNumber, () => route.params.lessonNumber],
	(
		[newChapterNumber, newLessonNumber],
		[oldChapterNumber, oldLessonNumber]
	) => {
		if (newChapterNumber && newLessonNumber) {
			lesson.submit({
				chapter: newChapterNumber,
				lesson: newLessonNumber,
			})
		}
	}
)

const redirectToLogin = () => {
	window.location.href = `/login?redirect_to=/courses/${props.courseName}/learn/${route.params.chapterNumber}-${route.params.lessonNumber}`
}

const allowDiscussions = () => {
	return (
		lesson.data?.membership ||
		user.data?.is_moderator ||
		user.data?.is_instructor
	)
}

const allowEdit = () => {
	if (user.data?.is_moderator) return true
	if (lesson.data?.instructors.includes(user.data?.name)) return true
	return false
}

const allowInstructorContent = () => {
	if (user.data?.is_moderator) return true
	if (lesson.data?.instructors.includes(user.data?.name)) return true
	return false
}
</script>
<style>
.avatar-group {
	display: inline-flex;
	align-items: center;
}

.avatar-group .avatar {
	transition: margin 0.1s ease-in-out;
}

.lesson-content p {
	margin-bottom: 1rem;
	line-height: 1.7;
}

.lesson-content li {
	line-height: 1.7;
}

.lesson-content ol {
	list-style: auto;
	margin: revert;
	padding: 1rem;
}

.lesson-content ul {
	list-style: auto;
	padding: 1rem;
	margin: revert;
}

.lesson-content img {
	border: 1px solid theme('colors.gray.200');
	border-radius: 0.5rem;
}

.lesson-content code {
	display: block;
	overflow-x: auto;
	padding: 1rem 1.25rem;
	background: #011627;
	color: #d6deeb;
	border-radius: 0.5rem;
	margin: 1rem 0;
}

.lesson-content a {
	color: theme('colors.gray.900');
	text-decoration: underline;
	font-weight: 500;
}

.codex-editor__redactor {
	padding-bottom: 0 !important;
}

.embed-tool__caption {
	display: none;
}
</style>
