import { useState, useEffect } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import { 
    ChevronLeft, 
    CheckCircle2, 
    Circle, 
    Play, 
    FileText, 
    ChevronRight, 
    Menu, 
    X,
    Lock,
    ArrowLeft,
    CheckCircle,
    ChevronDown
} from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { Progress } from '@/Components/ui/progress';
import { Sheet, SheetContent } from '@/Components/ui/sheet';

interface Lesson {
    id: number;
    title: string;
    slug: string;
    content: string | null;
    video_url: string | null;
    duration: number | null;
}

interface Module {
    id: number;
    title: string;
    lessons: Lesson[];
}

interface Course {
    id: number;
    name: string;
    slug: string;
    modules: Module[];
}

interface ProgressItem {
    course_lesson_id: number;
}

interface Props {
    course: Course;
    currentLesson?: Lesson;
    progress: ProgressItem[];
}

export default function Player({ course, currentLesson, progress }: Props) {
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [openModules, setOpenModules] = useState<number[]>([]);
    const [isDesktop, setIsDesktop] = useState(true);

    useEffect(() => {
        const handleResize = () => {
            setIsDesktop(window.innerWidth >= 1024);
        };
        // Set initial value
        handleResize();
        
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    useEffect(() => {
        // Only set default sidebar state once on mount
        if (window.innerWidth >= 1024) {
            setSidebarOpen(true);
        } else {
            setSidebarOpen(false);
        }

        // Open current module by default once on mount
        const activeLesson = currentLesson || course.modules[0]?.lessons[0];
        const currentModule = course.modules.find(m => m.lessons.some(l => l.id === activeLesson?.id));
        if (currentModule) {
            setOpenModules([currentModule.id]);
        }
    }, [course.id]); // Only run when switching courses, not lessons

    const toggleModule = (moduleId: number) => {
        setOpenModules(prev => 
            prev.includes(moduleId) 
                ? prev.filter(id => id !== moduleId) 
                : [...prev, moduleId]
        );
    };
    
    // Find the first lesson if none is selected
    const activeLesson = currentLesson || course.modules[0]?.lessons[0];
    
    const isCompleted = (lessonId: number) => {
        return progress.some(p => p.course_lesson_id === lessonId);
    };

    const totalLessons = course.modules.reduce((acc, m) => acc + m.lessons.length, 0);
    const completedLessons = progress.length;
    const progressPercentage = Math.round((completedLessons / totalLessons) * 100);

    // Helper to find next lesson
    const allLessons = course.modules.flatMap(m => m.lessons);
    const currentIndex = allLessons.findIndex(l => l.id === activeLesson?.id);
    const nextLesson = allLessons[currentIndex + 1];

    // Embed Video Helper
    const getEmbedUrl = (url: string) => {
        if (url.includes('youtube.com') || url.includes('youtu.be')) {
            const id = url.includes('youtu.be') ? url.split('/').pop() : new URL(url).searchParams.get('v');
            return `https://www.youtube.com/embed/${id}?modestbranding=1&rel=0&showinfo=0&iv_load_policy=3&controls=1&autohide=1&disablekb=1`;
        }
        if (url.includes('vimeo.com')) {
            const id = url.split('/').pop();
            return `https://player.vimeo.com/video/${id}`;
        }
        return url;
    };

    return (
        <div className="flex flex-col h-screen bg-white">
            <Head title={activeLesson ? `${activeLesson.title} - ${course.name}` : course.name} />
            
            {/* Top Header */}
            <header className="h-16 border-b border-[#E8E6DF] flex items-center justify-between px-6 bg-white z-20 flex-shrink-0">
                <div className="flex items-center gap-4">
                    <Link 
                        href={route('learning.index')}
                        className="p-2 hover:bg-[#F5F3EF] rounded-xl transition-colors text-ink"
                    >
                        <ArrowLeft className="h-5 w-5" />
                    </Link>
                    <div className="hidden sm:block">
                        <h1 className="text-[14px] font-bold text-ink truncate max-w-[300px]">
                            {course.name}
                        </h1>
                        <div className="flex items-center gap-2 mt-0.5">
                            <div className="w-32">
                                <Progress value={progressPercentage} className="h-1" />
                            </div>
                            <span className="text-[10px] font-bold text-[#8C92AC] uppercase tracking-wider">
                                {progressPercentage}% Complete
                            </span>
                        </div>
                    </div>
                </div>

                <div className="flex items-center gap-3">
                    <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => setSidebarOpen(!sidebarOpen)}
                        className={`rounded-xl font-bold text-[12px] gap-2 transition-all ${sidebarOpen ? 'bg-primary/5 text-primary' : 'text-[#8C92AC]'}`}
                    >
                        {sidebarOpen ? <X className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
                        <span className="hidden sm:inline">{sidebarOpen ? 'Close Menu' : 'Curriculum'}</span>
                        <span className="sm:hidden">Curriculum</span>
                    </Button>
                </div>
            </header>

            <div className="flex flex-1 overflow-hidden">
                {/* Main Content Area */}
                <main className="flex-1 overflow-y-auto bg-[#FAFAF8]">
                    {activeLesson ? (
                        <div className="max-w-5xl mx-auto py-12 px-6 lg:px-12">
                            {/* Video Player */}
                            {activeLesson.video_url && (
                                <div className="aspect-video w-full rounded-[2.5rem] overflow-hidden bg-black shadow-2xl mb-12">
                                    <iframe 
                                        src={getEmbedUrl(activeLesson.video_url)}
                                        className="w-full h-full"
                                        allowFullScreen
                                    />
                                </div>
                            )}

                            {/* Course Completion Celebration */}
                            {progressPercentage === 100 && (
                                <div className="mb-8 p-6 bg-emerald-50 border border-emerald-100 rounded-[2.5rem] flex flex-col sm:flex-row items-center gap-6 animate-in fade-in slide-in-from-top-4 duration-700">
                                    <div className="h-16 w-16 bg-emerald-500 rounded-2xl flex items-center justify-center flex-shrink-0 shadow-lg shadow-emerald-200">
                                        <CheckCircle className="h-8 w-8 text-white" />
                                    </div>
                                    <div className="text-center sm:text-left flex-1">
                                        <h3 className="text-lg font-bold text-emerald-900">Congratulations! Course Completed!</h3>
                                        <p className="text-emerald-700/80 text-sm font-medium">You've successfully completed all the lessons in this course.</p>
                                    </div>
                                    <Link 
                                        href={route('learning.index')}
                                        className="h-12 px-8 bg-emerald-500 text-white font-bold text-sm rounded-2xl hover:bg-emerald-600 transition-all flex items-center gap-2 shadow-lg shadow-emerald-200"
                                    >
                                        Back to Dashboard
                                    </Link>
                                </div>
                            )}

                            {/* Lesson Content */}
                            <div className="bg-white rounded-[3rem] border border-[#E8E6DF] p-8 md:p-12 shadow-sm">
                                <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-12">
                                    <div>
                                        <h2 className="font-display text-[2rem] text-ink leading-tight mb-2">
                                            {activeLesson.title}
                                        </h2>
                                        {activeLesson.duration && (
                                            <span className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider">
                                                Duration: {activeLesson.duration} minutes
                                            </span>
                                        )}
                                    </div>
                                    
                                    {!isCompleted(activeLesson.id) ? (
                                        <Button 
                                            onClick={() => {
                                                const nextUrl = nextLesson ? route('learning.lesson', [course.slug, nextLesson.slug]) : route('learning.index');
                                                router.post(route('learning.complete', activeLesson.id), { next_url: nextUrl }, { 
                                                    preserveScroll: false, 
                                                    preserveState: false 
                                                });
                                            }}
                                            className="h-12 px-8 rounded-2xl bg-primary text-white font-bold text-[14px] hover:brightness-110 shadow-lg shadow-primary/20"
                                        >
                                            Complete Lesson
                                        </Button>
                                    ) : (
                                        <div className="flex items-center gap-2 text-emerald-600 font-bold bg-emerald-50 px-6 py-3 rounded-2xl border border-emerald-100">
                                            <CheckCircle className="h-5 w-5" />
                                            Lesson Completed
                                        </div>
                                    )}
                                </div>

                                <div className="prose prose-ink max-w-none prose-p:text-lg prose-p:leading-relaxed prose-headings:font-display">
                                    {activeLesson.content ? (
                                        <div dangerouslySetInnerHTML={{ __html: activeLesson.content }} />
                                    ) : (
                                        <p className="text-[#8C92AC] italic">No text content for this lesson.</p>
                                    )}
                                </div>

                                {/* Bottom Completion Button for better UX */}
                                {!isCompleted(activeLesson.id) && (
                                    <div className="mt-12 p-8 bg-primary/5 rounded-[2rem] border border-primary/10 text-center">
                                        <h4 className="text-lg font-bold text-ink mb-4">Finished with this lesson?</h4>
                                        <Button 
                                            onClick={() => {
                                                const nextUrl = nextLesson ? route('learning.lesson', [course.slug, nextLesson.slug]) : route('learning.index');
                                                router.post(route('learning.complete', activeLesson.id), { next_url: nextUrl }, { 
                                                    preserveScroll: false, 
                                                    preserveState: false 
                                                });
                                            }}
                                            className="h-12 px-12 rounded-2xl bg-primary text-white font-bold text-[14px] hover:brightness-110 shadow-lg shadow-primary/20"
                                        >
                                            Complete Lesson & Continue
                                        </Button>
                                    </div>
                                )}

                                {/* Navigation Footer */}
                                <div className="mt-12 pt-8 border-t border-[#E8E6DF] flex flex-col sm:flex-row items-center justify-between gap-4">
                                    {currentIndex > 0 ? (
                                        <Link 
                                            href={route('learning.lesson', [course.slug, allLessons[currentIndex - 1].slug])}
                                            className="inline-flex h-12 w-full sm:w-auto items-center justify-center gap-3 px-8 bg-white border border-[#E8E6DF] rounded-2xl text-[13px] font-bold text-ink hover:border-primary/50 transition-all"
                                            preserveScroll
                                            preserveState
                                        >
                                            <ChevronLeft className="h-5 w-5" />
                                            Previous Lesson
                                        </Link>
                                    ) : <div className="hidden sm:block" />}

                                    {nextLesson && (
                                        <button 
                                            onClick={() => {
                                                if (!isCompleted(activeLesson!.id)) {
                                                    router.post(route('learning.complete', activeLesson!.id), {
                                                        next_url: route('learning.lesson', [course.slug, nextLesson.slug])
                                                    }, {
                                                        preserveScroll: true,
                                                        preserveState: true
                                                    });
                                                } else {
                                                    router.visit(route('learning.lesson', [course.slug, nextLesson.slug]), {
                                                        preserveScroll: true,
                                                        preserveState: true
                                                    });
                                                }
                                            }}
                                            className="inline-flex h-12 w-full sm:w-auto items-center justify-center gap-3 px-8 bg-white border border-[#E8E6DF] rounded-2xl text-[13px] font-bold text-ink hover:border-primary/50 transition-all"
                                        >
                                            <span className="truncate">Next: {nextLesson.title}</span>
                                            <ChevronRight className="h-4 w-4 flex-shrink-0" />
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div className="flex flex-col items-center justify-center h-full text-center p-6">
                            <Lock className="h-16 w-16 text-[#C0BDBA] mb-4" />
                            <h2 className="text-2xl font-bold text-ink">No lesson selected</h2>
                            <p className="text-[#8C92AC]">Please select a lesson from the curriculum sidebar to start learning.</p>
                        </div>
                    )}
                </main>

                {/* Mobile Curriculum Drawer (Sheet) */}
                {!isDesktop && (
                    <div className="lg:hidden">
                        <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
                            <SheetContent side="right" className="w-[85%] max-w-[400px] p-0 border-l border-[#E8E6DF] bg-white sm:max-w-sm [&>button]:hidden">
                                <div className="h-full flex flex-col overflow-hidden">
                                    <div className="p-6 border-b border-[#E8E6DF] flex items-center justify-between flex-shrink-0">
                                        <div className="flex items-center gap-3">
                                            <button 
                                                onClick={() => setSidebarOpen(false)}
                                                className="p-2 hover:bg-[#F5F3EF] rounded-lg transition-colors text-ink -ml-2"
                                            >
                                                <ArrowLeft className="h-5 w-5" />
                                            </button>
                                            <div>
                                                <h3 className="font-bold text-ink text-lg">Course Curriculum</h3>
                                                <p className="text-[11px] text-[#8C92AC] font-bold uppercase tracking-wider mt-1">
                                                    {completedLessons} / {totalLessons} Lessons Completed
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex-1 overflow-y-auto">
                                        <CurriculumList 
                                            course={course}
                                            activeLesson={activeLesson}
                                            openModules={openModules}
                                            toggleModule={toggleModule}
                                            isDesktop={isDesktop}
                                            setSidebarOpen={setSidebarOpen}
                                            isCompleted={isCompleted}
                                        />
                                    </div>
                                </div>
                            </SheetContent>
                        </Sheet>
                    </div>
                )}

                {/* Desktop Curriculum Sidebar */}
                <aside 
                    className={`
                        hidden lg:flex flex-col bg-white transition-all duration-300 ease-in-out
                        shadow-none border-l border-[#E8E6DF] flex-shrink-0 overflow-hidden
                        ${sidebarOpen ? 'w-[400px] min-w-[400px]' : 'w-0 min-w-0 border-none p-0'}
                    `}
                >
                    <div className="w-[400px] flex-shrink-0 h-full flex flex-col overflow-hidden">
                        <div className="p-6 border-b border-[#E8E6DF] flex items-center justify-between flex-shrink-0">
                            <div className="flex items-center gap-3">
                                <button 
                                    onClick={() => setSidebarOpen(false)}
                                    className="p-2 hover:bg-[#F5F3EF] rounded-lg transition-colors text-ink -ml-2"
                                >
                                    <ArrowLeft className="h-5 w-5" />
                                </button>
                                <div>
                                    <h3 className="font-bold text-ink text-lg">Course Curriculum</h3>
                                    <p className="text-[11px] text-[#8C92AC] font-bold uppercase tracking-wider mt-1">
                                        {completedLessons} / {totalLessons} Lessons Completed
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div className="flex-1 overflow-y-auto">
                            <CurriculumList 
                                course={course}
                                activeLesson={activeLesson}
                                openModules={openModules}
                                toggleModule={toggleModule}
                                isDesktop={isDesktop}
                                setSidebarOpen={setSidebarOpen}
                                isCompleted={isCompleted}
                            />
                        </div>
                    </div>
                </aside>
            </div>
        </div>
    );
}

// Sub-component defined outside to prevent remounting
const CurriculumList = ({ 
    course, 
    activeLesson, 
    openModules, 
    toggleModule, 
    isDesktop, 
    setSidebarOpen,
    isCompleted
}: {
    course: Course;
    activeLesson: Lesson | undefined;
    openModules: number[];
    toggleModule: (id: number) => void;
    isDesktop: boolean;
    setSidebarOpen: (open: boolean) => void;
    isCompleted: (id: number) => boolean;
}) => (
    <div className="p-4 space-y-2">
        {course.modules.map((module) => {
            const isOpen = openModules.includes(module.id);
            return (
                <div key={module.id} className="space-y-1">
                    <button 
                        onClick={() => toggleModule(module.id)}
                        className="w-full flex items-center justify-between px-4 py-3 text-[11px] font-bold text-[#8C92AC] uppercase tracking-widest bg-[#FAFAF8] rounded-xl hover:bg-[#F5F3EF] transition-colors"
                    >
                        {module.title}
                        <ChevronDown className={`h-4 w-4 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`} />
                    </button>
                    
                    {isOpen && (
                        <div className="space-y-1 pt-1">
                            {module.lessons.map((lesson) => (
                                <Link
                                    key={lesson.id}
                                    href={route('learning.lesson', [course.slug, lesson.slug])}
                                    onClick={() => {
                                        if (!isDesktop) {
                                            setSidebarOpen(false);
                                        }
                                    }}
                                    preserveScroll
                                    preserveState
                                    className={`flex items-center gap-3 p-4 rounded-2xl transition-all group ${
                                        activeLesson?.id === lesson.id 
                                            ? 'bg-primary/5 border border-primary/20' 
                                            : 'hover:bg-[#F5F3EF] border border-transparent'
                                    }`}
                                >
                                    {isCompleted(lesson.id) ? (
                                        <CheckCircle2 className="h-5 w-5 text-emerald-500 fill-emerald-50" />
                                    ) : (
                                        <div className={`h-5 w-5 rounded-full border-2 ${
                                            activeLesson?.id === lesson.id ? 'border-primary' : 'border-[#E8E6DF]'
                                        } flex items-center justify-center`}>
                                            {lesson.video_url ? <Play className={`h-2.5 w-2.5 ${
                                                activeLesson?.id === lesson.id ? 'fill-primary text-primary' : 'text-transparent'
                                            }`} /> : <div className="h-1.5 w-1.5 bg-transparent rounded-full" />}
                                        </div>
                                    )}
                                    <div className="flex-1 min-w-0">
                                        <p className={`text-[13px] font-bold truncate ${
                                            activeLesson?.id === lesson.id ? 'text-primary' : 'text-ink'
                                        }`}>
                                            {lesson.title}
                                        </p>
                                        {lesson.duration !== null && lesson.duration > 0 && (
                                            <span className="text-[10px] text-[#8C92AC] font-bold">
                                                {lesson.duration}m
                                            </span>
                                        )}
                                    </div>
                                </Link>
                            ))}
                        </div>
                    )}
                </div>
            );
        })}
    </div>
);
