import { Head, Link, router, useHttp } from '@inertiajs/react';
import {
    Bookmark,
    BookmarkCheck,
    BookOpen,
    Bot,
    CheckCircle2,
    ChevronDown,
    ChevronLeft,
    ChevronRight,
    Circle,
    ClipboardList,
    FileText,
    MessageSquare,
    NotebookPen,
    Play,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type SimpleLesson = { id: number; title: string; type: string; order: number };
type SimpleQuiz = { id: number; title: string; order: number };
type SimpleAssignment = { id: number; title: string; order: number };
type Chapter = {
    id: number;
    title: string;
    order: number;
    lessons: SimpleLesson[];
    quizzes: SimpleQuiz[];
    assignments: SimpleAssignment[];
};

type Lesson = {
    id: number;
    title: string;
    type: 'video' | 'article' | 'text' | 'pdf' | 'file';
    content: string | null;
    video_url: string | null;
    file_path: string | null;
    duration_minutes: number;
    chapter: { id: number; course_id: number };
};

type NavigationItem = { id: number; type: 'lesson' | 'quiz' | 'assignment'; url: string } | null;

type Props = {
    course: { id: number; title: string; slug: string; chapters: Chapter[] };
    lesson: Lesson;
    enrollment: { id: number; target_completion_date: string | null };
    completedLessonIds: number[];
    progress: { total: number; completed: number; percent: number };
    isBookmarked: boolean;
    note: string | null;
    prev_item: NavigationItem;
    next_item: NavigationItem;
};

const BRAND = '#118AB2';
const SUCCESS = '#06D6A0';

function lessonTypeIcon(type: string) {
    if (type === 'video') return <Play className="h-3.5 w-3.5" />;
    if (type === 'pdf' || type === 'file') return <FileText className="h-3.5 w-3.5" />;
    return <BookOpen className="h-3.5 w-3.5" />;
}

export default function LearningShow({
    course,
    lesson,
    enrollment,
    completedLessonIds,
    progress,
    isBookmarked: initialBookmarked,
    note: initialNote,
    prev_item,
    next_item,
}: Props) {
    const [openChapters, setOpenChapters] = useState<Record<number, boolean>>({ [lesson.chapter.id]: true });
    const [showNotes, setShowNotes] = useState(!!initialNote);
    const [noteContent, setNoteContent] = useState(initialNote ?? '');
    const [bookmarked, setBookmarked] = useState(initialBookmarked);
    const noteTimer = useRef<ReturnType<typeof setTimeout>>();
    const http = useHttp({ content: initialNote ?? '' });
    const isCompleted = completedLessonIds.includes(lesson.id);

    useEffect(() => {
        setNoteContent(initialNote ?? '');
        setBookmarked(initialBookmarked);
        http.setData({ content: initialNote ?? '' });
        setShowNotes(!!initialNote);
    }, [lesson.id]);

    function markComplete() {
        router.patch(`/courses/${course.slug}/learn/${lesson.id}/complete`, {}, { preserveScroll: true });
    }

    async function toggleBookmark() {
        const originalState = bookmarked;
        // Optimistic update: toggle state instantly for zero-latency UI response
        setBookmarked(!originalState);

        try {
            const response = (await http.post(`/bookmarks/lessons/${lesson.id}`, {})) as { bookmarked: boolean };
            if (response && typeof response.bookmarked === 'boolean') {
                setBookmarked(response.bookmarked);
            }
        } catch (error) {
            // Rollback to original state if the request fails
            setBookmarked(originalState);
        }
    }

    function handleNoteChange(value: string) {
        setNoteContent(value);
        http.setData('content', value);
    }

    function saveNote() {
        http.put(`/lessons/${lesson.id}/note`);
    }

    return (
        <>
            <Head title={`${lesson.title} — ${course.title}`} />

            <div className="flex h-[calc(100vh-64px)]" style={{ backgroundColor: '#F5F6F8' }}>

                {/* ── SIDEBAR ────────────────────────────────────────────── */}
                <aside
                    className="hidden lg:flex flex-col shrink-0 overflow-hidden"
                    style={{
                        width: 292,
                        backgroundColor: '#FFFFFF',
                        borderRight: '1px solid rgba(0,0,0,0.08)',
                    }}
                >
                    {/* Course header */}
                    <div className="shrink-0 p-4" style={{ borderBottom: '1px solid rgba(0,0,0,0.07)' }}>
                        <Link
                            href={`/my-courses/${course.slug}`}
                            className="mb-3 inline-flex items-center gap-1 text-xs transition-colors"
                            style={{ color: '#AAAAAA' }}
                            onMouseEnter={(e) => (e.currentTarget.style.color = BRAND)}
                            onMouseLeave={(e) => (e.currentTarget.style.color = '#AAAAAA')}
                        >
                            <ChevronLeft className="h-3 w-3" />
                            Kelas Saya
                        </Link>

                        <p className="text-base font-semibold leading-snug" style={{ color: '#1A1A1A' }}>
                            {course.title}
                        </p>

                        <div className="mt-3">
                            <div className="mb-1.5 flex items-center justify-between text-sm" style={{ color: '#BBBBBB' }}>
                                <span>{progress.completed}/{progress.total} materi selesai</span>
                                <span className="font-semibold" style={{ color: BRAND }}>{progress.percent}%</span>
                            </div>
                            <div className="h-1.5 overflow-hidden rounded-full" style={{ backgroundColor: 'rgba(0,0,0,0.07)' }}>
                                <div
                                    className="h-full rounded-full transition-all duration-500"
                                    style={{ width: `${progress.percent}%`, backgroundColor: BRAND }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Chapter list */}
                    <div className="flex-1 overflow-y-auto">
                        {course.chapters.map((chapter, idx) => {
                            const isOpen = !!openChapters[chapter.id];
                            const hasActiveLesson = chapter.lessons.some((l) => l.id === lesson.id);

                            return (
                                <div key={chapter.id} style={{ borderBottom: '1px solid rgba(0,0,0,0.05)' }}>
                                    {/* Chapter header */}
                                    <button
                                        onClick={() => setOpenChapters(prev => ({ ...prev, [chapter.id]: !prev[chapter.id] }))}
                                        className="flex w-full items-center gap-2.5 px-4 py-3 text-left transition-colors"
                                        style={{
                                            backgroundColor: isOpen ? 'rgba(17,138,178,0.03)' : 'transparent',
                                        }}
                                    >
                                        <span
                                            className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold"
                                            style={
                                                hasActiveLesson
                                                    ? { backgroundColor: BRAND, color: '#FFFFFF' }
                                                    : { backgroundColor: 'rgba(0,0,0,0.08)', color: '#888888' }
                                            }
                                        >
                                            {idx + 1}
                                        </span>
                                        <span className="flex-1 text-sm font-semibold leading-snug" style={{ color: '#2A2A2A' }}>
                                            {chapter.title}
                                        </span>
                                        <ChevronDown
                                            className="h-3.5 w-3.5 shrink-0 transition-transform"
                                            style={{
                                                color: '#CCCCCC',
                                                transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                                            }}
                                        />
                                    </button>

                                    {/* Lesson / quiz / assignment items */}
                                    {isOpen && (
                                        <div style={{ backgroundColor: 'rgba(0,0,0,0.01)' }}>
                                            {chapter.lessons.map((l) => {
                                                const done = completedLessonIds.includes(l.id);
                                                const active = l.id === lesson.id;
                                                return (
                                                    <Link
                                                        key={l.id}
                                                        href={`/courses/${course.slug}/learn/${l.id}`}
                                                        className="flex items-center gap-2.5 py-2.5 pr-4 transition-colors"
                                                        style={{
                                                            paddingLeft: active ? 13 : 16,
                                                            borderLeft: `3px solid ${active ? BRAND : 'transparent'}`,
                                                            backgroundColor: active ? 'rgba(17,138,178,0.06)' : 'transparent',
                                                        }}
                                                        onMouseEnter={(e) => {
                                                            if (!active) e.currentTarget.style.backgroundColor = 'rgba(0,0,0,0.03)';
                                                        }}
                                                        onMouseLeave={(e) => {
                                                            if (!active) e.currentTarget.style.backgroundColor = 'transparent';
                                                        }}
                                                    >
                                                        <span
                                                            className="shrink-0"
                                                            style={{ color: done ? SUCCESS : active ? BRAND : '#CCCCCC' }}
                                                        >
                                                            {done ? <CheckCircle2 className="h-3.5 w-3.5" /> : lessonTypeIcon(l.type)}
                                                        </span>
                                                        <span
                                                            className="line-clamp-2 text-sm leading-snug"
                                                            style={{
                                                                color: active ? BRAND : done ? '#BBBBBB' : '#555555',
                                                                fontWeight: active ? 600 : 400,
                                                                textDecoration: done ? 'line-through' : 'none',
                                                            }}
                                                        >
                                                            {l.title}
                                                        </span>
                                                    </Link>
                                                );
                                            })}

                                            {chapter.quizzes.map((q) => (
                                                <Link
                                                    key={`q-${q.id}`}
                                                    href={`/courses/${course.slug}/quiz/${q.id}`}
                                                    className="flex items-center gap-2.5 px-4 py-2.5 transition-colors"
                                                    onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = 'rgba(255,183,3,0.06)')}
                                                    onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
                                                >
                                                    <ClipboardList className="h-3.5 w-3.5 shrink-0" style={{ color: '#D4A000' }} />
                                                    <span className="line-clamp-2 text-sm leading-snug" style={{ color: '#555555' }}>
                                                        {q.title}
                                                    </span>
                                                </Link>
                                            ))}

                                            {chapter.assignments.map((a) => (
                                                <Link
                                                    key={`a-${a.id}`}
                                                    href={`/courses/${course.slug}/assignment/${a.id}`}
                                                    className="flex items-center gap-2.5 px-4 py-2.5 transition-colors"
                                                    onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = 'rgba(99,102,241,0.06)')}
                                                    onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
                                                >
                                                    <FileText className="h-3.5 w-3.5 shrink-0" style={{ color: '#6366F1' }} />
                                                    <span className="line-clamp-2 text-sm leading-snug" style={{ color: '#555555' }}>
                                                        {a.title}
                                                    </span>
                                                </Link>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </aside>

                {/* ── MAIN CONTENT ───────────────────────────────────────── */}
                <main className="flex flex-1 flex-col overflow-hidden">

                    {/* Scrollable lesson body */}
                    <div className="flex-1 overflow-y-auto">
                        <div className="mx-auto max-w-3xl px-5 py-8">

                            {/* Title */}
                            <h1 className="mb-6 text-xl font-bold leading-snug" style={{ color: '#1A1A1A' }}>
                                {lesson.title}
                            </h1>

                            {/* Video */}
                            {lesson.type === 'video' && lesson.video_url && (
                                <div
                                    className="mb-6 overflow-hidden rounded-2xl bg-black"
                                    style={{ boxShadow: '0 4px 24px rgba(0,0,0,0.14)' }}
                                >
                                    {lesson.video_url.includes('youtube') || lesson.video_url.includes('youtu.be') ? (
                                        <div className="relative pt-[56.25%]">
                                            <iframe
                                                src={lesson.video_url.replace('watch?v=', 'embed/')}
                                                className="absolute inset-0 h-full w-full"
                                                allowFullScreen
                                            />
                                        </div>
                                    ) : (
                                        <video src={lesson.video_url} controls className="w-full" />
                                    )}
                                </div>
                            )}

                            {/* PDF / File */}
                            {(lesson.type === 'pdf' || lesson.type === 'file') && lesson.file_path && (
                                <div className="mb-6">
                                    <a
                                        href={`/storage/${lesson.file_path}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="inline-flex items-center gap-2.5 rounded-xl px-4 py-3 text-sm font-medium transition-all"
                                        style={{
                                            color: BRAND,
                                            backgroundColor: 'rgba(17,138,178,0.08)',
                                            border: '1px solid rgba(17,138,178,0.15)',
                                        }}
                                        onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = 'rgba(17,138,178,0.14)')}
                                        onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'rgba(17,138,178,0.08)')}
                                    >
                                        <FileText className="h-4 w-4" />
                                        Buka / Unduh File
                                    </a>
                                </div>
                            )}

                            {/* Article / Text */}
                            {(lesson.type === 'article' || lesson.type === 'text') && lesson.content && (
                                <div
                                    className="rounded-2xl bg-white px-7 py-6"
                                    style={{
                                        border: '1px solid rgba(0,0,0,0.07)',
                                        boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
                                    }}
                                >
                                    <div className="prose prose-sm max-w-none dark:prose-invert">
                                        <style dangerouslySetInnerHTML={{ __html: `
                                            .prose iframe {
                                                max-width: 100% !important;
                                                width: 100% !important;
                                                height: auto !important;
                                                aspect-ratio: 16 / 9 !important;
                                                border-radius: 12px;
                                            }
                                            .prose [data-youtube-video] {
                                                width: 100% !important;
                                                max-width: 100% !important;
                                                height: auto !important;
                                            }
                                        `}} />
                                        <div dangerouslySetInnerHTML={{ __html: lesson.content }} />
                                    </div>
                                </div>
                            )}
                            {/* Notes panel */}
                            {showNotes && (
                                <div
                                    className="mt-6 rounded-2xl bg-white px-7 py-6"
                                    style={{
                                        border: '1px solid rgba(0,0,0,0.07)',
                                        boxShadow: '0 2px 12px rgba(0,0,0,0.04)',
                                    }}
                                >
                                    <p className="mb-2 text-xs font-semibold uppercase tracking-wide" style={{ color: '#AAAAAA' }}>
                                        Catatan
                                    </p>
                                                                    <textarea
                                        value={noteContent}
                                        onChange={(e) => handleNoteChange(e.target.value)}
                                        rows={4}
                                        placeholder="Tulis catatan untuk materi ini..."
                                        className="w-full resize-none rounded-xl px-3.5 py-2.5 text-sm outline-none transition-colors"
                                        style={{
                                            border: '1px solid rgba(0,0,0,0.12)',
                                            color: '#333333',
                                            backgroundColor: '#FAFAFA',
                                        }}
                                        onFocus={(e) => (e.currentTarget.style.borderColor = BRAND)}
                                        onBlur={(e) => (e.currentTarget.style.borderColor = 'rgba(0,0,0,0.12)')}
                                    />
                                    <div className="mt-3 flex justify-end items-center gap-3">
                                        {http.processing && (
                                            <span className="text-xs text-zinc-400">Menyimpan...</span>
                                        )}
                                        {http.wasSuccessful && !http.processing && (
                                            <span className="text-xs text-emerald-500 font-bold">Catatan tersimpan!</span>
                                        )}
                                        <button
                                            onClick={saveNote}
                                            disabled={http.processing}
                                            className="rounded-xl px-4 py-2 text-xs font-semibold text-white transition-all active:scale-95 cursor-pointer disabled:opacity-50"
                                            style={{ backgroundColor: BRAND }}
                                        >
                                            Simpan Catatan
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Navigation & Controls */}
                            <div className="mt-8 flex items-center justify-between border-t pt-6" style={{ borderColor: 'rgba(0,0,0,0.08)' }}>
                                {/* Left: Prev button */}
                                <div className="w-1/4 flex justify-start">
                                    {prev_item ? (
                                        <Link
                                            href={prev_item.url}
                                            className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold text-gray-600 transition-all hover:bg-gray-50 hover:-translate-y-0.5 active:translate-y-0"
                                            style={{ borderColor: 'rgba(0,0,0,0.08)', backgroundColor: '#FFFFFF' }}
                                        >
                                            <ChevronLeft className="h-4 w-4" />
                                            Sebelumnya
                                        </Link>
                                    ) : (
                                        <div />
                                    )}
                                </div>

                                {/* Middle: Status, completion, tools */}
                                <div className="flex items-center gap-3 justify-center">
                                    {/* Completion badge */}
                                    <span
                                        className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium"
                                        style={
                                            isCompleted
                                                ? { backgroundColor: 'rgba(6,214,160,0.12)', color: SUCCESS }
                                                : { backgroundColor: 'rgba(0,0,0,0.05)', color: '#999999' }
                                        }
                                    >
                                        {isCompleted
                                            ? <><CheckCircle2 className="h-3.5 w-3.5" />Selesai</>
                                            : <><Circle className="h-3.5 w-3.5" />Belum selesai</>
                                        }
                                    </span>

                                    {/* Tools */}
                                    <div className="flex items-center gap-1">
                                        <button
                                            onClick={toggleBookmark}
                                            title={bookmarked ? 'Hapus bookmark' : 'Bookmark materi ini'}
                                            className="rounded-lg p-2 transition-all duration-200 hover:scale-115 active:scale-90 text-zinc-300 hover:text-zinc-500 cursor-pointer"
                                            style={bookmarked ? { color: BRAND } : undefined}
                                        >
                                            {bookmarked ? (
                                                <BookmarkCheck className="h-4 w-4 transition-transform duration-300 scale-105" style={{ color: BRAND }} />
                                            ) : (
                                                <Bookmark className="h-4 w-4 transition-transform duration-300 scale-100" />
                                            )}
                                        </button>

                                        <button
                                            onClick={() => setShowNotes(!showNotes)}
                                            title="Catatan"
                                            className="rounded-lg p-2 transition-all duration-200 hover:scale-115 active:scale-90 text-zinc-300 hover:text-zinc-500 cursor-pointer"
                                            style={showNotes ? { color: BRAND } : undefined}
                                        >
                                            <NotebookPen className={`h-4 w-4 transition-transform duration-300 ${showNotes ? 'scale-105' : 'scale-100'}`} />
                                        </button>
                                    </div>

                                    {/* Complete CTA */}
                                    {!isCompleted && (
                                        <button
                                            onClick={markComplete}
                                            className="inline-flex items-center gap-2 rounded-xl px-5 py-2 text-sm font-semibold text-white transition-all hover:-translate-y-0.5 active:translate-y-0"
                                            style={{
                                                backgroundColor: BRAND,
                                                boxShadow: '0 4px 14px rgba(17,138,178,0.3)',
                                            }}
                                        >
                                            <CheckCircle2 className="h-4 w-4" />
                                            Tandai Selesai
                                        </button>
                                    )}
                                </div>

                                {/* Right: Next button */}
                                <div className="w-1/4 flex justify-end">
                                    {next_item ? (
                                        <Link
                                            href={next_item.url}
                                            className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold transition-all hover:-translate-y-0.5 active:translate-y-0"
                                            style={{
                                                borderColor: BRAND,
                                                color: BRAND,
                                                backgroundColor: '#FFFFFF',
                                            }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.backgroundColor = 'rgba(17,138,178,0.04)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.backgroundColor = '#FFFFFF';
                                            }}
                                        >
                                            Berikutnya
                                            <ChevronRight className="h-4 w-4" />
                                        </Link>
                                    ) : (
                                        <div />
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                </main>
            </div>
        </>
    );
}

LearningShow.layout = (page: React.ReactNode) => {
    const props = (page as React.ReactElement)?.props as Props | undefined;
    const breadcrumbs: BreadcrumbItem[] = props?.course
        ? [
              { title: 'Kelas Saya', href: '/my-courses' },
              { title: props.course.title, href: `/my-courses/${props.course.slug}` },
              { title: props.lesson.title, href: '#' },
          ]
        : [];
    return <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
};
