import { Head, Link } from '@inertiajs/react';
import {
    Award,
    BookOpen,
    CheckCircle2,
    ChevronLeft,
    ClipboardList,
    Clock,
    FileText,
    GraduationCap,
    Play,
    PlayCircle,
} from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import { cn } from '@/lib/utils';

type Lesson = { id: number; title: string; type: string; duration_minutes: number; order: number };
type Quiz = { id: number; title: string; duration_minutes: number; deadline: string | null; order: number };
type Assignment = { id: number; title: string; deadline: string | null; order: number };
type Chapter = { id: number; title: string; order: number; lessons: Lesson[]; quizzes: Quiz[]; assignments: Assignment[] };

type Props = {
    course: {
        id: number;
        title: string;
        slug: string;
        thumbnail: string | null;
        description: string | null;
        level: string;
        duration_minutes: number;
        instructor: { id: number; name: string; bio: string | null };
        category: { id: number; name: string } | null;
        chapters: Chapter[];
    };
    enrollment: {
        id: number;
        status: 'active' | 'completed';
        target_completion_date: string | null;
        enrolled_at: string | null;
    };
    completedLessonIds: number[];
    completedQuizIds: number[];
    completedAssignmentIds: number[];
    progress: { total: number; completed: number; percent: number };
};

const levelLabels: Record<string, string> = {
    beginner: 'Pemula',
    intermediate: 'Menengah',
    advanced: 'Mahir',
};

function formatDuration(minutes: number): string {
    if (minutes < 60) return `${minutes} menit`;
    const h = Math.floor(minutes / 60);
    const m = minutes % 60;
    return m > 0 ? `${h} jam ${m} menit` : `${h} jam`;
}

function lessonTypeLabel(type: string): string {
    if (type === 'video') return 'Video';
    if (type === 'pdf') return 'Dokumen PDF';
    return 'Materi';
}

function LessonIcon({ type, done }: { type: string; done: boolean }) {
    if (done) return <CheckCircle2 className="h-5 w-5" />;
    if (type === 'video') return <PlayCircle className="h-5 w-5" />;
    if (type === 'pdf') return <FileText className="h-5 w-5" />;
    return <BookOpen className="h-5 w-5" />;
}

export default function MyCourseShow({
    course,
    enrollment,
    completedLessonIds,
    completedQuizIds,
    completedAssignmentIds,
    progress,
}: Props) {
    const completedLessonSet = new Set(completedLessonIds);
    const completedQuizSet = new Set(completedQuizIds);
    const completedAssignmentSet = new Set(completedAssignmentIds);
    const isCompleted = enrollment.status === 'completed';

    const allLessons = course.chapters.flatMap((ch) => ch.lessons);
    const nextLesson = allLessons.find((l) => !completedLessonSet.has(l.id)) ?? allLessons[0];

    const totalQuizzes = course.chapters.reduce((s, ch) => s + ch.quizzes.length, 0);
    const totalAssignments = course.chapters.reduce((s, ch) => s + ch.assignments.length, 0);

    return (
        <>
            <Head title={course.title} />

            {/* Pastel page background */}
            <div className="min-h-screen bg-sky-50/40">
                <div className="mx-auto max-w-3xl px-5 py-8">
                    {/* Back */}
                    <Link
                        href="/my-courses"
                        className="mb-6 inline-flex items-center gap-1.5 text-sm text-slate-400 transition-colors hover:text-sky-500"
                    >
                        <ChevronLeft className="h-4 w-4" />
                        Kelas Saya
                    </Link>

                    {/* ── COURSE HEADER ─────────────────────────────────── */}
                    <div className="mb-8 overflow-hidden rounded-3xl border border-sky-100 bg-white shadow-sm shadow-sky-100">
                        {/* Thumbnail */}
                        {course.thumbnail ? (
                            <div className="relative h-52 w-full overflow-hidden">
                                <img src={course.thumbnail} alt={course.title} className="h-full w-full object-cover" />
                                <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent" />
                                {isCompleted && (
                                    <div className="absolute top-4 right-4 flex items-center gap-1.5 rounded-full bg-teal-200 px-3 py-1.5 text-xs font-semibold text-teal-800">
                                        <Award className="h-3.5 w-3.5" />
                                        Selesai
                                    </div>
                                )}
                            </div>
                        ) : (
                            <div className="flex h-40 w-full items-center justify-center bg-gradient-to-br from-sky-100 to-blue-100">
                                <GraduationCap className="h-12 w-12 text-sky-300" />
                            </div>
                        )}

                        <div className="p-6">
                            {course.category && (
                                <span className="mb-2 inline-block rounded-full bg-sky-100 px-2.5 py-0.5 text-xs font-semibold text-sky-600">
                                    {course.category.name}
                                </span>
                            )}
                            <h1 className="text-xl font-bold leading-snug text-slate-800 md:text-2xl">
                                {course.title}
                            </h1>
                            <p className="mt-1 text-sm text-slate-400">
                                oleh {course.instructor.name} · {levelLabels[course.level] ?? course.level} ·{' '}
                                {formatDuration(course.duration_minutes)}
                            </p>

                            {/* Progress */}
                            <div className="mt-5">
                                <div className="mb-2 flex items-center justify-between">
                                    <span className="text-sm text-slate-500">
                                        {progress.completed} dari {progress.total} materi selesai
                                    </span>
                                    <span
                                        className={cn(
                                            'text-sm font-bold',
                                            progress.percent === 100 ? 'text-teal-500' : 'text-sky-500',
                                        )}
                                    >
                                        {progress.percent}%
                                    </span>
                                </div>
                                <div className="h-3 overflow-hidden rounded-full bg-sky-100">
                                    <div
                                        className={cn(
                                            'h-full rounded-full transition-all duration-500',
                                            progress.percent === 100 ? 'bg-teal-300' : 'bg-sky-300',
                                        )}
                                        style={{ width: `${progress.percent}%` }}
                                    />
                                </div>
                            </div>

                            {/* Stats row */}
                            <div className="mt-4 flex flex-wrap gap-3 text-sm text-slate-400">
                                <span className="flex items-center gap-1.5">
                                    <BookOpen className="h-4 w-4 text-sky-400" />
                                    {allLessons.length} materi
                                </span>
                                {totalQuizzes > 0 && (
                                    <span className="flex items-center gap-1.5">
                                        <ClipboardList className="h-4 w-4 text-amber-400" />
                                        {totalQuizzes} kuis
                                    </span>
                                )}
                                {totalAssignments > 0 && (
                                    <span className="flex items-center gap-1.5">
                                        <FileText className="h-4 w-4 text-indigo-400" />
                                        {totalAssignments} tugas
                                    </span>
                                )}
                                {enrollment.target_completion_date && (
                                    <span className="flex items-center gap-1.5">
                                        <Clock className="h-4 w-4 text-teal-400" />
                                        Target:{' '}
                                        {new Date(enrollment.target_completion_date).toLocaleDateString('id-ID', {
                                            day: 'numeric',
                                            month: 'long',
                                            year: 'numeric',
                                        })}
                                    </span>
                                )}
                            </div>

                            {/* CTA */}
                            {nextLesson && (
                                <div className="mt-5">
                                    <Link
                                        href={`/courses/${course.slug}/learn/${nextLesson.id}`}
                                        className="flex w-full items-center justify-center gap-2 rounded-2xl bg-sky-400 py-3.5 text-base font-semibold text-white shadow-md shadow-sky-200 transition-all hover:-translate-y-0.5 hover:bg-sky-500 active:translate-y-0"
                                    >
                                        <Play className="h-5 w-5" />
                                        {progress.completed === 0 ? 'Mulai Belajar' : 'Lanjutkan Belajar'}
                                    </Link>
                                </div>
                            )}
                            {!nextLesson && (
                                <div className="mt-5">
                                    <div className="flex w-full items-center justify-center gap-2 rounded-2xl bg-teal-200 py-3.5 text-base font-semibold text-teal-800">
                                        <Award className="h-5 w-5" />
                                        Kelas Sudah Selesai!
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* ── CURRICULUM ──────────────────────────────────────── */}
                    <h2 className="mb-4 text-lg font-bold text-slate-700">Daftar Materi</h2>

                    <div className="flex flex-col gap-4">
                        {course.chapters.map((chapter, idx) => {
                            const chapterLessons = chapter.lessons;
                            const chapterCompletedLessons = chapterLessons.filter((l) => completedLessonSet.has(l.id)).length;
                            const chapterCompletedQuizzes = chapter.quizzes.filter((q) => completedQuizSet.has(q.id)).length;
                            const chapterCompletedAssignments = chapter.assignments.filter((a) => completedAssignmentSet.has(a.id)).length;
                            const chapterCompleted = chapterCompletedLessons + chapterCompletedQuizzes + chapterCompletedAssignments;
                            const chapterTotal = chapterLessons.length + chapter.quizzes.length + chapter.assignments.length;
                            const chapterDone =
                                chapterTotal > 0 &&
                                chapterLessons.every((l) => completedLessonSet.has(l.id)) &&
                                chapter.quizzes.every((q) => completedQuizSet.has(q.id)) &&
                                chapter.assignments.every((a) => completedAssignmentSet.has(a.id));

                            return (
                                <div
                                    key={chapter.id}
                                    className={cn(
                                        'overflow-hidden rounded-2xl border bg-white shadow-sm',
                                        chapterDone ? 'border-teal-100 shadow-teal-50' : 'border-sky-100 shadow-sky-50',
                                    )}
                                >
                                    {/* Chapter header */}
                                    <div
                                        className={cn(
                                            'flex items-center gap-4 px-5 py-4',
                                            chapterDone
                                                ? 'bg-gradient-to-r from-teal-50 to-white'
                                                : 'bg-gradient-to-r from-sky-50 to-white',
                                        )}
                                    >
                                        <span
                                            className={cn(
                                                'flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-bold shadow-sm',
                                                chapterDone
                                                    ? 'bg-teal-200 text-teal-700 shadow-teal-100'
                                                    : 'bg-sky-200 text-sky-700 shadow-sky-100',
                                            )}
                                        >
                                            {chapterDone ? <CheckCircle2 className="h-5 w-5" /> : idx + 1}
                                        </span>
                                        <div className="min-w-0 flex-1">
                                            <h3 className="truncate font-bold text-slate-700">{chapter.title}</h3>
                                        </div>
                                        <span
                                            className={cn(
                                                'shrink-0 rounded-full px-2.5 py-1 text-xs font-semibold',
                                                chapterDone
                                                    ? 'bg-teal-100 text-teal-600'
                                                    : 'bg-sky-100 text-sky-600',
                                            )}
                                        >
                                            {chapterCompleted}/{chapterTotal} selesai
                                        </span>
                                    </div>

                                    {/* Items */}
                                    {chapterTotal > 0 && (
                                        <div className="divide-y divide-slate-50 px-4 pb-2 pt-1">
                                            {chapter.lessons.map((lesson) => {
                                                const done = completedLessonSet.has(lesson.id);
                                                return (
                                                    <Link
                                                        key={lesson.id}
                                                        href={`/courses/${course.slug}/learn/${lesson.id}`}
                                                        className="group flex items-center gap-4 py-3.5"
                                                    >
                                                        <div
                                                            className={cn(
                                                                'flex h-11 w-11 shrink-0 items-center justify-center rounded-xl',
                                                                done
                                                                    ? 'bg-teal-100 text-teal-500'
                                                                    : 'bg-sky-100 text-sky-500 group-hover:bg-sky-200',
                                                            )}
                                                        >
                                                            <LessonIcon type={lesson.type} done={done} />
                                                        </div>
                                                        <div className="min-w-0 flex-1">
                                                            <p
                                                                className={cn(
                                                                    'font-medium text-sm md:text-base break-words whitespace-normal',
                                                                    done ? 'text-slate-400' : 'text-slate-700 group-hover:text-sky-600',
                                                                )}
                                                            >
                                                                {lesson.title}
                                                            </p>
                                                            <p className="text-xs text-slate-400">
                                                                {lessonTypeLabel(lesson.type)}
                                                                {lesson.duration_minutes > 0 && ` · ${lesson.duration_minutes} menit`}
                                                            </p>
                                                        </div>
                                                        {done ? (
                                                            <CheckCircle2 className="h-5 w-5 text-teal-500 shrink-0" />
                                                        ) : (
                                                            <Play className="h-5 w-5 text-sky-500 group-hover:text-sky-600 shrink-0 transition-colors" />
                                                        )}
                                                    </Link>
                                                );
                                            })}

                                            {chapter.quizzes.map((quiz) => {
                                                const done = completedQuizSet.has(quiz.id);
                                                return (
                                                    <Link
                                                        key={`q-${quiz.id}`}
                                                        href={`/courses/${course.slug}/quiz/${quiz.id}`}
                                                        className="group flex items-center gap-4 py-3.5"
                                                    >
                                                        <div
                                                            className={cn(
                                                                'flex h-11 w-11 shrink-0 items-center justify-center rounded-xl',
                                                                done
                                                                    ? 'bg-teal-100 text-teal-500'
                                                                    : 'bg-amber-100 text-amber-500 group-hover:bg-amber-200',
                                                            )}
                                                        >
                                                            {done ? (
                                                                <CheckCircle2 className="h-5 w-5" />
                                                            ) : (
                                                                <ClipboardList className="h-5 w-5" />
                                                            )}
                                                        </div>
                                                        <div className="min-w-0 flex-1">
                                                            <p
                                                                className={cn(
                                                                    'font-medium text-sm md:text-base break-words whitespace-normal',
                                                                    done ? 'text-slate-400' : 'text-slate-700 group-hover:text-amber-600',
                                                                )}
                                                            >
                                                                {quiz.title}
                                                            </p>
                                                            <p className="text-xs text-slate-400">
                                                                Kuis · {quiz.duration_minutes} menit
                                                                {quiz.deadline && (
                                                                    <>
                                                                        {' · Deadline: '}
                                                                        {new Date(quiz.deadline).toLocaleDateString('id-ID', {
                                                                            day: 'numeric',
                                                                            month: 'long',
                                                                        })}
                                                                    </>
                                                                )}
                                                            </p>
                                                        </div>
                                                        {done ? (
                                                            <CheckCircle2 className="h-5 w-5 text-teal-500 shrink-0" />
                                                        ) : (
                                                            <Play className="h-5 w-5 text-amber-500 group-hover:text-amber-600 shrink-0 transition-colors" />
                                                        )}
                                                    </Link>
                                                );
                                            })}

                                            {chapter.assignments.map((assignment) => {
                                                const done = completedAssignmentSet.has(assignment.id);
                                                return (
                                                    <Link
                                                        key={`a-${assignment.id}`}
                                                        href={`/courses/${course.slug}/assignment/${assignment.id}`}
                                                        className="group flex items-center gap-4 py-3.5"
                                                    >
                                                        <div
                                                            className={cn(
                                                                'flex h-11 w-11 shrink-0 items-center justify-center rounded-xl',
                                                                done
                                                                    ? 'bg-teal-100 text-teal-500'
                                                                    : 'bg-indigo-100 text-indigo-400 group-hover:bg-indigo-200',
                                                            )}
                                                        >
                                                            {done ? (
                                                                <CheckCircle2 className="h-5 w-5" />
                                                            ) : (
                                                                <FileText className="h-5 w-5" />
                                                            )}
                                                        </div>
                                                        <div className="min-w-0 flex-1">
                                                            <p
                                                                className={cn(
                                                                    'font-medium text-sm md:text-base break-words whitespace-normal',
                                                                    done ? 'text-slate-400' : 'text-slate-700 group-hover:text-indigo-600',
                                                                )}
                                                            >
                                                                {assignment.title}
                                                            </p>
                                                            <p className="text-xs text-slate-400">
                                                                Tugas
                                                                {assignment.deadline && (
                                                                    <>
                                                                        {' · Deadline: '}
                                                                        {new Date(assignment.deadline).toLocaleDateString('id-ID', {
                                                                            day: 'numeric',
                                                                            month: 'long',
                                                                        })}
                                                                    </>
                                                                )}
                                                            </p>
                                                        </div>
                                                        {done ? (
                                                            <CheckCircle2 className="h-5 w-5 text-teal-500 shrink-0" />
                                                        ) : (
                                                            <Play className="h-5 w-5 text-indigo-500 group-hover:text-indigo-600 shrink-0 transition-colors" />
                                                        )}
                                                    </Link>
                                                );
                                            })}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        </>
    );
}

MyCourseShow.layout = (page: React.ReactNode) => <AppLayout>{page}</AppLayout>;
