"use client";

import { useEffect, useRef, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { 
    Loader2, ArrowLeft, MoreHorizontal, MessageSquare, ChevronDown, 
    Check, X, ArrowRight, Award, Download, Lock, CheckCircle, 
    FileText, Loader, Globe 
} from "lucide-react";
import axios from "axios";
import { BASE_URL } from "@/utils/url";
import { USER_TOKEN_CL } from "@/utils/data/user-client";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/cn";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { useFormSubmission } from "@/hooks/use-form-submission";
import { toast } from "@/hooks/use-toast";
import { useLocale, useTranslations } from "next-intl";
import { LanguageSwitcher } from "@/components/appearance/language";

type LaunchResponse = {
    success: boolean;
    course: {
        id: number;
        title: string;
        entry_point_url: string;
        scorm_version: string;
    };
    user: {
        id: number;
        name: string;
    };
};

    type StructureItem = {
    title: string;
    identifier?: string;
    resource_href?: string;
    children?: StructureItem[];
};

export default function ScormLaunchPage() {
    const searchParams = useSearchParams();
    const router = useRouter();
    const groupId = searchParams.get("groupId");
    const scormId = searchParams.get("scormId");

    const [loading, setLoading] = useState(true);
    const [course, setCourse] = useState<LaunchResponse["course"] | null>(null);
    const [structure, setStructure] = useState<StructureItem[]>([]);
    const [activeTab, setActiveTab] = useState<"null" | "menu" | "comments" | null>("null");
    const [currentUrl, setCurrentUrl] = useState<string>("");
    const [canDownloadCertificate, setCanDownloadCertificate] = useState(false);
    const [showCompletion, setShowCompletion] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [isFetching, setIsFetching] = useState(false);
    const [progressStats, setProgressStats] = useState<{
        progress: number;
        statistics?: string;
        details?: Record<string, string>;
    } | null>(null);
    const [userId, setUserId] = useState<number | null>(null);
    const [currentLessonName, setCurrentLessonName] = useState<string>("");

    const locale = useLocale();
    const isArabic = locale === "ar";
    // Check if translations exist for programs
    let t: any;
    try {
        t = useTranslations('programs');
    } catch (e) {
        // Fallback or ignore
    }

    const scormFrameRef = useRef<HTMLIFrameElement | null>(null);
    const scormDataRef = useRef<Record<string, any>>({});
    const isDirtyRef = useRef(false);
    const isInitializedRef = useRef(false);
    const timerRef = useRef<any>(null);
    const token = USER_TOKEN_CL();

    // ✅ Proxy URL Transformation Helper
    function getProxyUrl(url: string) {
        let finalUrl = url;
        if (finalUrl.includes("https://tr.ivorytraining.com")) {
            finalUrl = finalUrl.replace("https://tr.ivorytraining.com", "/scorm-proxy/staging");
        } else if (finalUrl.includes("https://tr.ivorytraining.com")) {
            finalUrl = finalUrl.replace("https://tr.ivorytraining.com", "/scorm-proxy/tr");
        } else if (finalUrl.includes("https://e-training.ivorytraining.com")) {
            finalUrl = finalUrl.replace("https://e-training.ivorytraining.com", "/scorm-proxy/e-training");
        } else if (finalUrl.includes("https://ivorytraining.com")) {
             finalUrl = finalUrl.replace("https://ivorytraining.com", "/scorm-proxy/prod");
        }
        return finalUrl;
    }

    // ✅ Fetch launch info
    async function launchCourse() {
        if (!groupId) throw new Error("Missing Group ID");
        const res = await axios.get(`${BASE_URL}/user/scorm/${groupId}/launch`, {
            headers: { Authorization: `Bearer ${token}` }
        });
        const json: LaunchResponse = res.data;
        
        console.log("🎯 Launch Response:", json);
        
        if (!json.success) throw new Error("Launch failed");

        // Use helper
        json.course.entry_point_url = getProxyUrl(json.course.entry_point_url);
        
        setCourse(json.course);
        setUserId(json.user.id);
        setCurrentUrl(json.course.entry_point_url);
        return json; 
    }

    // ✅ Fetch Structure (Menu)
    async function fetchStructure(scormCourseId: number) {
        try {
            const targetId = scormId || scormCourseId;
            const res = await axios.get(`${BASE_URL}/user/scorm/${targetId}/structure`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            if (Array.isArray(res.data)) {
                setStructure(res.data);
            }
        } catch (e) {
            console.error("Failed to load structure", e);
        }
    }

    // ✅ Load Progress
    async function loadProgress(scormCourseId: number, userId: number) {
        setIsFetching(true);
        try {
            // 1. SCORM Specific Progress
            const res = await axios.get(`${BASE_URL}/user/scorm/progress?course_id=${scormCourseId}&user_id=${userId}`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            const json = res.data;
            console.log("📈 SCORM Progress Loaded:", json);
            if (json.success) {
                if (json.progress?.details) {
                    scormDataRef.current = { ...json.progress.details };
                }
                if (json.can_download_certificate) {
                    setCanDownloadCertificate(true);
                }
                setProgressStats(prev => ({
                    progress: json.progress_percentage || json.progress || prev?.progress || 0,
                    statistics: json.statistics || prev?.statistics,
                    details: json.details || prev?.details
                }));
            }

            // 2. Group / Program Progress (As requested by user)
            if (groupId) {
                const groupRes = await axios.get(`${BASE_URL}/user/progress_in_group/${groupId}`, {
                    headers: { Authorization: `Bearer ${token}` }
                });
                console.log("📊 Group Progress Loaded:", groupRes.data);
                if (groupRes.data?.success) {
                    if (groupRes.data.can_download_certificate) {
                        setCanDownloadCertificate(true);
                    }
                    setProgressStats(prev => ({
                        progress: groupRes.data.progress_percentage || groupRes.data.progress || prev?.progress || 0,
                        statistics: groupRes.data.statistics || prev?.statistics,
                        details: groupRes.data.details || prev?.details
                    }));
                }
            }
        } catch (e) {
            console.error("Failed to load progress", e);
        } finally {
            setIsFetching(false);
        }
    }

    // ✅ Save Progress
    async function saveProgress(courseId: number, force = false) {
        if (!isInitializedRef.current || isSaving) return;
        if (!isDirtyRef.current && !force) return;
        
        setIsSaving(true);
        isDirtyRef.current = false; // Reset early to catch next changes
        // Use user-specified format
        const payload = {
            course_id: String(courseId),
            data: Object.keys(scormDataRef.current).length === 0 ? [] : scormDataRef.current,
            lesson_name: scormDataRef.current["cmi.lesson_location"] || "Lesson", // fallback
            exam_notes: scormDataRef.current["cmi.suspend_data"] || "",
            objectives: [],
        };
        try {
            const res = await axios.post(`${BASE_URL}/user/scorm/progress`, payload, {
                headers: { Authorization: `Bearer ${token}` }
            });
            
            if (res.data?.success) {
                if (res.data.can_download_certificate) {
                    setCanDownloadCertificate(true);
                }
                setProgressStats(prev => ({
                    progress: res.data.progress_percentage || res.data.progress || prev?.progress || 0,
                    statistics: res.data.statistics || prev?.statistics,
                    details: res.data.details || prev?.details
                }));
            }

            // Also check group progress on save
             if (groupId) {
                const groupRes = await axios.get(`${BASE_URL}/user/progress_in_group/${groupId}`, {
                    headers: { Authorization: `Bearer ${token}` }
                });
                if (groupRes.data?.success) {
                    if (groupRes.data.can_download_certificate) {
                        setCanDownloadCertificate(true);
                    }
                    setProgressStats(prev => ({
                        progress: groupRes.data.progress_percentage || groupRes.data.progress || prev?.progress || 0,
                        statistics: groupRes.data.statistics || prev?.statistics,
                        details: groupRes.data.details || prev?.details
                    }));
                }
            }
        } catch (e) {
            console.error("Failed to save progress", e);
        } finally {
            setIsSaving(false);
        }
    }

    // ✅ Navigate to resource
    function navigateToResource(resourceHref: string | undefined) {
        if (!resourceHref || !course) return;
        
        // 1. Get Base URL from entry_point (remove index_lms.html or whatever is at end)
        // entry: .../scorm_courses/1/index_lms.html
        // base: .../scorm_courses/1/
        const baseUrl = course.entry_point_url.substring(0, course.entry_point_url.lastIndexOf('/') + 1);
        
        // 2. Combine
        const newUrl = baseUrl + resourceHref;
        
        console.log("Navigating to:", newUrl);
        setCurrentUrl(newUrl);
    }


    // SCORM APIs
    function createScorm2004Api(courseId: number) {
        return {
            Initialize: () => { isInitializedRef.current = true; return "true"; },
            Terminate: () => { saveProgress(courseId, true); isInitializedRef.current = false; return "true"; },
            GetValue: (key: string) => scormDataRef.current[key] ?? "",
            SetValue: (key: string, value: any) => { 
                scormDataRef.current[key] = value; 
                isDirtyRef.current = true;
                if (key === "cmi.lesson_location" || key === "cmi.core.lesson_location") {
                    setCurrentLessonName(value);
                }
                return "true"; 
            },
            Commit: () => { saveProgress(courseId, true); return "true"; },
            GetLastError: () => "0", GetErrorString: () => "No error", GetDiagnostic: () => "",
        };
    }
    function createScorm12Api(courseId: number, api2004: any) {
        return {
            LMSInitialize: () => api2004.Initialize(),
            LMSFinish: () => api2004.Terminate(),
            LMSGetValue: (key: string) => {
                 // Map 1.2 keys to 2004 keys if needed, or just pass through
                 // Common mapping: cmi.core.lesson_location -> cmi.location
                 return api2004.GetValue(key);
            },
            LMSSetValue: (key: string, value: any) => api2004.SetValue(key, value),
            LMSCommit: () => api2004.Commit(),
            LMSGetLastError: () => api2004.GetLastError(),
            LMSGetErrorString: () => api2004.GetErrorString(),
            LMSGetDiagnostic: () => api2004.GetDiagnostic(),
        };
    }

    useEffect(() => {
        async function init() {
            try {
                if (!groupId) return;
                setLoading(true);
                const launchData = await launchCourse();
                
                await Promise.all([
                    loadProgress(launchData.course.id, launchData.user.id),
                    fetchStructure(launchData.course.id)
                ]);

                const api2004 = createScorm2004Api(launchData.course.id);
                const api12 = createScorm12Api(launchData.course.id, api2004);
                (window as any).API_1484_11 = api2004;
                (window as any).API = api12;

                timerRef.current = setInterval(() => { saveProgress(launchData.course.id); }, 1000);
                setLoading(false);
            } catch (err) {
                console.error(err);
                setLoading(false);
            }
        }
        init();
        return () => { if (timerRef.current) clearInterval(timerRef.current); };
    }, [groupId]);

    const downloadCertificateHook = useFormSubmission({
        endPoint: `/user/certification/group/${groupId}`,
        method: "GET",
        onError: (err) => {
            const errorData = (err as any)?.response?.data;
            toast({
                variant: "destructive",
                title: errorData?.error || errorData?.message || "Failed to download certificate"
            });
            return { handled: true };
        },
        onSuccess: (response) => {
            const pdfUrl = response?.pdf_url;
            if (pdfUrl) {
                window.open(pdfUrl, "_blank");
            } else {
                toast({
                    variant: "destructive",
                    title: response?.error || response?.message || "Failed to download certificate"
                });
            }
        }
    });

    if (loading) {
        return (
            <div className="h-screen w-full grid place-items-center bg-white">
                <div className="flex flex-col items-center gap-2">
                    <Loader2 className="size-8 animate-spin text-blue-600" />
   
                </div>
            </div>
        )
    }

    if (!course) return null;

    if (showCompletion) {
        return (
            <div className="h-screen flex flex-col bg-gray-50 overflow-hidden font-sans rtl:[direction:rtl]">
                {/* Purple Header */}
                <div className="bg-gradient-to-r from-purple-700 via-purple-700 to-indigo-800 text-white px-6 py-4 flex-shrink-0 shadow-md">
                    <div className="max-w-4xl mx-auto flex items-center justify-between">
                        <div className="flex items-center gap-4">
                            <div className="bg-white/20 p-2 rounded-lg">
                                <Award className="size-6 text-white" />
                            </div>
                            <div>
                                <h2 className="text-lg font-bold leading-none mb-1">{isArabic ? "اكتمال المساق" : "Course Completion"}</h2>
                                <p className="text-xs text-white/70 truncate max-w-[200px]">{course.title}</p>
                            </div>
                        </div>
                        
                        <Button
                            onClick={() => setShowCompletion(false)}
                            variant="ghost"
                            size="sm"
                            className="bg-white text-purple-700 hover:bg-white/90 font-bold px-4 rounded-full"
                        >
                            {isArabic ? "العودة للمحتوى" : "Back to Course"}
                        </Button>
                    </div>
                </div>

                <div className="flex-1 flex items-center justify-center p-6 pb-24">
                    <div className="bg-white rounded-2xl shadow-xl p-10 flex flex-col items-center gap-6 max-w-md w-full border border-purple-100 text-center animate-in zoom-in-95 duration-300">
                        <div className="size-24 rounded-3xl bg-green-500 shadow-lg shadow-green-200 flex items-center justify-center transform transition-transform hover:scale-105">
                            <CheckCircle className="h-12 w-12 text-white" />
                        </div>
                        <div>
                            <h3 className="text-2xl font-bold text-gray-900 mb-2">
                                {isArabic ? "تهانينا! لقد أكملت الدورة بنجاح" : "Congratulations! You completed the course"}
                            </h3>
                            <p className="text-gray-500 text-sm max-w-xs mx-auto">
                                {isArabic 
                                    ? "لقد قمت بإكمال جميع متطلبات الدورة. يمكنك الآن تحميل شهادتك الاحترافية." 
                                    : "You have completed all course requirements. You can now download your professional certificate."}
                            </p>
                        </div>

                        <div className="w-full bg-purple-50 rounded-2xl p-4 border border-purple-100 mb-2">
                             <div className="flex items-center justify-between mb-2">
                                <span className="text-xs font-bold text-purple-700 uppercase tracking-wider">{isArabic ? "التقدم الإجمالي" : "Overall Progress"}</span>
                                <span className="text-xs font-bold text-purple-700">{progressStats?.progress || 100}%</span>
                             </div>
                             <div className="h-2 w-full bg-purple-200 rounded-full overflow-hidden mb-2">
                                <div className="h-full bg-purple-600 rounded-full" style={{ width: `${progressStats?.progress || 100}%` }} />
                             </div>
                             {progressStats?.statistics && (
                                <div className="text-[10px] text-purple-600 font-bold flex items-center justify-center gap-1">
                                    <FileText className="size-3" />
                                    {isArabic ? "الإحصائيات: " : "Statistics: "} {progressStats.statistics}
                                </div>
                             )}
                        </div>

                        <Button 
                            size="lg"
                            onClick={() => downloadCertificateHook.mutate({})}
                            disabled={downloadCertificateHook.isPending}
                            className="w-full h-14 text-lg font-bold rounded-xl shadow-lg bg-purple-600 hover:bg-purple-700 hover:shadow-xl active:scale-95 transition-all gap-2 group"
                        >
                            {downloadCertificateHook.isPending ? (
                                <Loader className="size-5 animate-spin" />
                            ) : (
                                <Download className="size-5 group-hover:animate-bounce" />
                            )}
                            {isArabic ? "تحميل الشهادة" : "Download Certificate"}
                        </Button>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="flex flex-col h-screen bg-gray-100 overflow-hidden font-sans">
            {/* Header - Modern Styled (Fullscreen Match) */}
            <header className="h-16 bg-gradient-to-r from-purple-600 via-purple-700 to-indigo-700 text-white px-4 md:px-6 sticky top-0 z-40 w-full shadow-lg flex items-center justify-between shrink-0">
                {/* Left side - Course info */}
                <div className="flex-1 flex items-center gap-3 min-w-0">
                    <Button 
                        variant="ghost" 
                        size="icon" 
                        onClick={() => {
                            if (window.opener) {
                                window.close();
                            } else {
                                router.back();
                            }
                        }}
                        className="text-white hover:bg-white/20 rounded-full shrink-0"
                    >
                        <ArrowLeft className="size-5 rtl:rotate-180" />
                    </Button>
                    <div className="min-w-0">
                        <h1 className="font-bold text-white text-base md:text-lg leading-tight line-clamp-1">
                            {course.title}
                        </h1>
                        <div className="flex items-center gap-2 text-xs text-purple-100/80">
                             <span className="font-medium truncate">
                                {currentLessonName || scormDataRef.current["cmi.lesson_location"] || scormDataRef.current["cmi.core.lesson_location"] || (isArabic ? "محتوى SCORM" : "SCORM Content")}
                             </span>
                        </div>
                    </div>
                </div>

                <div className="flex items-center gap-3 md:gap-6 flex-wrap">
                    {/* Circular Progress & Check Button */}
                    <div className="flex items-center gap-4">
                        {/* Progress Circle */}
                        <div className="relative size-12 shrink-0 flex items-center justify-center group" title={isArabic ? "التقدم الكلي" : "Total Progress"}>
                            <svg className="size-12 -rotate-90" viewBox="0 0 48 48">
                                <circle cx="24" cy="24" r="20" fill="none" stroke="rgba(255, 255, 255, 0.2)" strokeWidth="4" />
                                <circle
                                    cx="24" cy="24" r="20"
                                    fill="none" 
                                    stroke="white" 
                                    strokeWidth="4"
                                    strokeDasharray={2 * Math.PI * 20}
                                    strokeDashoffset={2 * Math.PI * 20 * (1 - (progressStats?.progress || 0) / 100)}
                                    strokeLinecap="round"
                                    className="transition-all duration-500"
                                />
                            </svg>
                            <div className="absolute inset-0 flex items-center justify-center">
                                <span className="text-xs font-bold text-white">
                                    {progressStats?.progress || 0}%
                                </span>
                            </div>
                        </div>

                        {/* Manual Check Process Button */}
                        {/* <Button
                            variant="outline"
                            size="sm"
                            onClick={() => userId && loadProgress(course.id, userId)} 
                            className="bg-white/10 hover:bg-white/20 border-white/20 text-white text-[10px] md:text-xs h-8 px-2 md:px-3 rounded-full gap-1.5 font-bold transition-all border group"
                        >
                            <Loader2 className={cn("size-3 md:size-3.5 group-hover:rotate-180 transition-transform duration-500", (isSaving || isFetching) && "animate-spin")} />
                            <span>{isArabic ? "تحديث الحالة" : "Check Progress"}</span>
                        </Button> */}
                    </div>

                    <div className="flex items-center gap-2">
                        <LanguageSwitcher 
                            seeLang={true} 
                            className="bg-white/10 hover:bg-white/20 border-white/10 text-white border-0 h-8 md:h-9 px-3 md:px-4 rounded- transition-all"
                        />
                        {canDownloadCertificate && (
                            <Button
                                onClick={() => setShowCompletion(true)}
                                size="sm"
                                className="bg-green-500 hover:bg-green-600 text-white border-0 font-bold px-3 md:px-4 rounded-full h-8 md:h-9 gap-2 shadow-[0_0_15px_rgba(34,197,94,0.4)] transition-all text-xs md:text-sm"
                            >
                                <Award className="size-3.5 md:size-4" />
                                <span className="hidden xs:inline">{isArabic ? "تحميل الشهادة" : "Download Certificate"}</span>
                            </Button>
                        )}
                        
                        {/* More Menu (if needed) */}
                       
                    </div>
                </div>
            </header>

            {/* Main Content Body */}
            <div className="flex flex-1 overflow-hidden">
                {/* Center: Player Area */}
                <div className="flex-1 flex flex-col items-center justify-center bg-[#f4f4f4] p-2 md:p-4 overflow-y-auto">
                    {/* Iframe Container - Card Effect */}
                    <div className="w-full h-full bg-white shadow-sm border border-gray-200 relative">
                         <iframe
                            ref={scormFrameRef}
                            src={currentUrl}
                            className="w-full h-full border-0"
                            allowFullScreen
                            sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-pointer-lock"
                            onError={(e) => {
                                console.error("❌ Iframe Load Error:", e);
                            }}
                            onLoad={() => {
                                console.log("✅ Iframe Loaded Successfully");
                            }}
                        />
                    </div>
                </div>

                {/* Menu Column */}
                {activeTab === "menu" && (
                    <div className="w-80 bg-white border-l border-gray-200 flex flex-col shrink-0 animate-in slide-in-from-right duration-200">
                        <div className="h-12 border-b border-gray-100 flex items-center justify-between px-4">
                            <span className="text-xs font-bold text-gray-500 tracking-wider">MENU</span>
                            <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setActiveTab(null)}>
                                <X className="size-4 text-gray-400" />
                            </Button>
                        </div>
                        <div className="flex-1 overflow-y-auto py-2">
                            {structure && structure.length > 0 ? (
                                structure.map((item, idx) => (
                                    <div key={idx} className="group">
                                        <div 
                                            className="px-4 py-3 text-sm text-gray-700 border-l-4 border-transparent hover:bg-gray-50 hover:border-gray-300 cursor-pointer flex items-center gap-3 transition-colors"
                                            onClick={() => navigateToResource(item.resource_href)}
                                        >
                                            <div className="size-4 rounded-full border border-gray-300 flex items-center justify-center shrink-0">
                                            </div>
                                            <span className="font-medium">{item.title}</span>
                                        </div>
                                        {item.children?.map((child, cIdx) => (
                                            <div 
                                                key={`${idx}-${cIdx}`} 
                                                className="pl-12 pr-4 py-2 text-sm text-gray-500 hover:bg-gray-50 cursor-pointer transition-colors"
                                                onClick={() => navigateToResource(child.resource_href)}
                                            >
                                                {child.title}
                                            </div>
                                        ))}
                                    </div>
                                ))
                            ) : (
                                <div className="p-4 text-sm text-gray-400 text-center">No menu available</div>
                            )}
                        </div>
                    </div>
                )}

                {/* Comments Column */}
                {activeTab === "comments" && (
                    <div className="w-80 bg-white border-l border-gray-200 flex flex-col shrink-0 animate-in slide-in-from-right duration-200">
                         <div className="h-12 border-b border-gray-100 flex items-center justify-between px-4">
                            <span className="font-bold text-gray-800 text-sm">Comments</span>
                            <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setActiveTab(null)}>
                                <X className="size-4 text-gray-400" />
                            </Button>
                        </div>
                        <div className="flex-1 overflow-y-auto bg-gray-50/30 p-4">
                             <div className="bg-white border border-gray-200 rounded p-3 flex gap-3 shadow-sm mb-4">
                                 <div className="shrink-0 bg-gray-200 rounded-full size-8 flex items-center justify-center text-xs">U</div>
                                 <div className="flex-1">
                                    <input 
                                        type="text" 
                                        placeholder="Add a comment..." 
                                        className="w-full text-sm outline-none placeholder:text-gray-400"
                                    />
                                 </div>
                             </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
