const { useState, useEffect } = React;
const { Button } = window.ReactApp.Components;
const { getPrograms, saveProgram, deleteProgram } = window.ReactApp.API;

window.ReactApp.AdminPrograms = () => {
    const [programs, setPrograms] = useState([]);
    const [loading, setLoading] = useState(true);
    const [editingProgram, setEditingProgram] = useState(null);

    useEffect(() => {
        loadData();
    }, []);

    useEffect(() => {
        if (window.lucide) {
            setTimeout(() => window.lucide.createIcons(), 50);
        }
    }, [programs, editingProgram, loading]);

    const loadData = async () => {
        setLoading(true);
        try {
            if (window.allPrograms && window.allPrograms.length) {
                setPrograms(window.allPrograms);
            } else {
                const data = await Promise.race([
                    getPrograms(),
                    new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 18000))
                ]);
                setPrograms(data || []);
            }
        } catch (e) {
            console.warn('AdminPrograms load:', e);
            setPrograms(window.allPrograms || []);
        }
        setLoading(false);
    };

    const handleSave = async (programData) => {
        await saveProgram(programData.id, programData);
        setEditingProgram(null);
        loadData();
        if (window.showNotification) window.showNotification("تم الحفظ بنجاح", "success");
    };

    const handleDelete = async (id) => {
        if(confirm("هل أنت متأكد من حذف هذا البرنامج؟")) {
            await deleteProgram(id);
            loadData();
            if (window.showNotification) window.showNotification("تم الحذف بنجاح", "success");
        }
    };

    if (editingProgram) {
        return <ProgramEditor program={editingProgram} onSave={handleSave} onCancel={() => setEditingProgram(null)} />;
    }

    return (
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
            <div className="flex justify-between items-center mb-6">
                <div>
                    <h2 className="text-2xl font-bold text-slate-800">إدارة البرامج الأكاديمية (نظام ديناميكي)</h2>
                    <p className="text-slate-500 text-sm mt-1">أضف وعدل البرامج والتفاصيل الأكاديمية بسهولة.</p>
                </div>
                <button type="button" className="adm-add-btn" onClick={() => setEditingProgram({})}>
                    <i data-lucide="plus-circle"></i> إضافة برنامج جديد
                </button>
            </div>

            {loading ? (
                <div className="text-center py-12 text-slate-500">جاري التحميل...</div>
            ) : (
                <div className="overflow-x-auto">
                    <table className="w-full text-right rtl">
                        <thead>
                            <tr className="bg-slate-50 text-slate-600 text-sm">
                                <th className="p-4 rounded-r-xl font-bold">اسم البرنامج</th>
                                <th className="p-4 font-bold">الكلية</th>
                                <th className="p-4 font-bold">الدرجة</th>
                                <th className="p-4 font-bold">الحالة</th>
                                <th className="p-4 rounded-l-xl font-bold">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            {programs.map(p => (
                                <tr key={p.id} className="border-b border-slate-50 hover:bg-slate-50/50 transition-colors">
                                    <td className="p-4 font-bold text-slate-800">{p.nameAr}</td>
                                    <td className="p-4 text-slate-600">{p.faculty}</td>
                                    <td className="p-4"><span className="bg-blue-50 text-blue-700 px-3 py-1 rounded-full text-xs font-bold">{p.degreeType}</span></td>
                                    <td className="p-4">
                                        <span className={`px-3 py-1 rounded-full text-xs font-bold ${p.isActive ? 'bg-emerald-50 text-emerald-700' : 'bg-rose-50 text-rose-700'}`}>
                                            {p.isActive ? 'نشط' : 'غير نشط'}
                                        </span>
                                    </td>
                                    <td className="p-4">
                                        <div className="adm-act-group">
                                            <button type="button" onClick={() => setEditingProgram(p)} className="adm-act-btn adm-act-edit" title="تعديل">
                                                <i data-lucide="pencil"></i><span>تعديل</span>
                                            </button>
                                            <button type="button" onClick={() => handleDelete(p.id)} className="adm-act-btn adm-act-del" title="حذف">
                                                <i data-lucide="trash-2"></i><span>حذف</span>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                            {programs.length === 0 && (
                                <tr>
                                    <td colSpan="5" className="text-center py-12 text-slate-500">لا توجد برامج مضافة حتى الآن.</td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
};

const ProgramEditor = ({ program, onSave, onCancel }) => {
    const [activeTab, setActiveTab] = useState('basic');
    const [loadingDetails, setLoadingDetails] = useState(false);
    
    const [formData, setFormData] = useState({
        nameAr: program.nameAr || program.name || '', 
        nameEn: program.nameEn || '', 
        degreeType: program.degreeType || program.degree || program.type || 'ماجستير', 
        faculty: program.faculty || program.college || 'الطب والعلوم الصحية',
        duration: program.duration || '', 
        creditHours: program.creditHours || program.hours || 0, 
        timing: program.timing || '', 
        studyMode: program.studyMode || 'انتظام',
        shortDescription: program.shortDescription || program.description || '', 
        bannerImage: program.bannerImage || program.image || '', 
        icon: program.icon || 'book', 
        isActive: program.isActive !== false,
        ...program
    });

    const [courses, setCourses] = useState([]);
    const [selectedFile, setSelectedFile] = useState(null);
    const [previewUrl, setPreviewUrl] = useState(program.bannerImage || program.image || '');
    const [uploading, setUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);

    useEffect(() => {
        if (program.id) {
            setLoadingDetails(true);
            window.ReactApp.API.getProgramDetails(program.id).then(details => {
                if(details && details.courses) setCourses(details.courses);
                setLoadingDetails(false);
            });
        }
    }, [program.id]);

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));
    };

    const handleFileChange = (e) => {
        if (e.target.files && e.target.files.length > 0) {
            const file = e.target.files[0];
            if (file.size > 5 * 1024 * 1024) {
                if (window.showNotification) window.showNotification("حجم الصورة كبير جداً، الحد الأقصى 5 ميجابايت", "error");
                return;
            }
            setSelectedFile(file);
            setPreviewUrl(URL.createObjectURL(file));
        }
    };

    const handleRemoveSelectedFile = () => {
        setSelectedFile(null);
        setPreviewUrl(formData.bannerImage || formData.image || '');
    };

    const handleAddCourse = () => {
        setCourses([...courses, { id: Date.now().toString(), titleAr: '', titleEn: '', creditHours: 3, semester: 'مقررات إجبارية', courseType: 'Core' }]);
    };

    const handleCourseChange = (id, field, value) => {
        setCourses(courses.map(c => {
            if (c.id !== id) return c;
            var next = { ...c, [field]: value };
            if (field === 'semester') {
                if (value === 'مقررات اختيارية') next.courseType = 'Elective';
                else if (value === 'مقررات استدراكية') next.courseType = 'Remedial';
                else next.courseType = 'Core';
            }
            return next;
        }));
    };

    const handleRemoveCourse = (id) => {
        setCourses(courses.filter(c => c.id !== id));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setUploading(true);
        
        let updatedFormData = { ...formData };
        
        try {
            if (selectedFile) {
                setUploadProgress(0);
                // Delete old storage file if editing
                if (program.id && program.bannerImage) {
                    await window.ReactApp.API.deleteStorageFile(program.bannerImage);
                }
                if (program.id && program.image && program.image !== program.bannerImage) {
                    await window.ReactApp.API.deleteStorageFile(program.image);
                }
                
                const downloadURL = await window.ReactApp.API.uploadProgramBannerImage(selectedFile, (progress) => {
                    setUploadProgress(progress);
                });
                
                updatedFormData.bannerImage = downloadURL;
                updatedFormData.image = downloadURL; // Keep both in sync for legacy compatibility
            }
            
            // 1. Save Basic Info
            const savedId = await window.ReactApp.API.saveProgram(updatedFormData.id, updatedFormData);
            
            // 2. Save Subcollections if we have them
            if (courses.length > 0 || program.id) {
                await window.ReactApp.API.saveSubCollection(savedId, 'courses', courses);
            }
            
            onSave({ id: savedId, ...updatedFormData });
        } catch (err) {
            console.error("Error during program save:", err);
            if (window.showNotification) window.showNotification("فشل حفظ البيانات أو رفع الصورة", "error");
        } finally {
            setUploading(false);
        }
    };

    return (
        <div className="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 text-right rtl">
            <div className="flex justify-between items-center mb-6 pb-4 border-b border-slate-100">
                <h2 className="text-2xl font-bold text-slate-800">{program.id ? 'تعديل البرنامج' : 'إضافة برنامج جديد'}</h2>
                <Button variant="secondary" onClick={onCancel}>إلغاء</Button>
            </div>
            
            <div className="flex gap-4 mb-6 border-b border-slate-100 pb-2">
                <button type="button" onClick={() => setActiveTab('basic')} className={`px-4 py-2 font-bold ${activeTab === 'basic' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-slate-500'}`}>البيانات الأساسية</button>
                <button type="button" onClick={() => setActiveTab('courses')} disabled={!program.id && !formData.nameAr} className={`px-4 py-2 font-bold ${activeTab === 'courses' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-slate-500'} ${!program.id && !formData.nameAr ? 'opacity-50 cursor-not-allowed' : ''}`}>المواد والخطة</button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
                {activeTab === 'basic' && (
                    <>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">اسم البرنامج (عربي) *</label>
                                <input type="text" name="nameAr" value={formData.nameAr} onChange={handleChange} required className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-blue-500 outline-none" />
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">اسم البرنامج (انجليزي)</label>
                                <input type="text" name="nameEn" value={formData.nameEn} onChange={handleChange} className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-blue-500 outline-none" />
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">الدرجة العلمية</label>
                                <select name="degreeType" value={formData.degreeType} onChange={handleChange} className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none">
                                    <option value="دبلوم عالي">دبلوم عالي</option>
                                    <option value="ماجستير">ماجستير</option>
                                    <option value="دكتوراه">دكتوراه</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">الكلية</label>
                                <select name="faculty" value={formData.faculty} onChange={handleChange} className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none">
                                    <option value="الطب والعلوم الصحية">الطب والعلوم الصحية</option>
                                    <option value="الهندسة والحاسبات">الهندسة والحاسبات</option>
                                    <option value="العلوم الإدارية والإنسانية">العلوم الإدارية والإنسانية</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">مدة الدراسة</label>
                                <input type="text" name="duration" value={formData.duration} onChange={handleChange} placeholder="مثال: سنتان (4 فصول)" className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none" />
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">إجمالي الساعات المعتمدة</label>
                                <input type="number" name="creditHours" value={formData.creditHours} onChange={handleChange} className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl outline-none" />
                            </div>
                            <div>
                                <label className="block text-sm font-bold text-slate-700 mb-2">حالة البرنامج</label>
                                <label className="flex items-center gap-2 cursor-pointer mt-3">
                                    <input type="checkbox" name="isActive" checked={formData.isActive} onChange={handleChange} className="w-5 h-5 rounded text-blue-600 focus:ring-blue-500" />
                                    <span className="text-slate-700 font-semibold">مفعل ويظهر للطلاب</span>
                                </label>
                            </div>
                            <div className="md:col-span-2 bg-slate-50 p-6 rounded-2xl border border-slate-200 mt-4">
                                <label className="block text-sm font-bold text-slate-700 mb-3">صورة البرنامج الأكاديمي</label>
                                
                                <div className="flex flex-col md:flex-row gap-6 items-center">
                                    {/* Preview Container */}
                                    <div className="relative w-full md:w-48 h-32 rounded-xl overflow-hidden bg-slate-200 border border-slate-300 shadow-inner flex items-center justify-center shrink-0">
                                        {previewUrl ? (
                                            <img src={previewUrl} alt="Preview" className="w-full h-full object-cover" />
                                        ) : (
                                            <div className="flex flex-col items-center justify-center text-slate-400">
                                                <span className="pointer-events-none mb-1"><i data-lucide="image" className="w-10 h-10"></i></span>
                                                <span className="text-xs">لا توجد صورة</span>
                                            </div>
                                        )}
                                        {uploading && (
                                            <div className="absolute inset-0 bg-slate-900/70 flex flex-col items-center justify-center text-white px-2 z-20">
                                                <div className="w-8 h-8 border-2 border-white/20 border-t-white rounded-full animate-spin mb-2"></div>
                                                <span className="text-xs font-bold font-poppins">{Math.round(uploadProgress)}%</span>
                                            </div>
                                        )}
                                    </div>
                                    
                                    {/* File Input & Controls */}
                                    <div className="flex-grow w-full space-y-3">
                                        <div className="relative border-2 border-dashed border-slate-300 hover:border-blue-500 rounded-xl p-6 transition-colors bg-white text-center cursor-pointer">
                                            <input 
                                                type="file" 
                                                accept="image/*" 
                                                onChange={handleFileChange}
                                                disabled={uploading}
                                                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" 
                                            />
                                            <div className="flex flex-col items-center justify-center gap-1 text-slate-500 pointer-events-none">
                                                <span className="pointer-events-none text-blue-500 mb-1"><i data-lucide="upload-cloud" className="w-8 h-8 animate-pulse"></i></span>
                                                <span className="text-sm font-bold text-slate-700">اسحب الصورة هنا أو انقر للاختيار</span>
                                                <span className="text-xs text-slate-400">يدعم صيغ JPG, PNG, WEBP (بحد أقصى 5 ميجابايت)</span>
                                            </div>
                                        </div>
                                        
                                        {selectedFile && (
                                            <div className="flex items-center justify-between bg-blue-50 p-2.5 rounded-lg border border-blue-100 text-xs">
                                                <div className="flex items-center gap-2 text-blue-700 font-bold">
                                                    <span className="pointer-events-none"><i data-lucide="file-text" className="w-4 h-4"></i></span>
                                                    <span className="truncate max-w-[200px]">{selectedFile.name}</span>
                                                    <span className="text-slate-400 font-normal">({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)</span>
                                                </div>
                                                <button 
                                                    type="button" 
                                                    onClick={handleRemoveSelectedFile} 
                                                    disabled={uploading}
                                                    className="text-rose-600 hover:bg-rose-50 p-1 rounded-md transition-colors"
                                                    title="إلغاء الملف المختار"
                                                >
                                                    <span className="pointer-events-none"><i data-lucide="x" className="w-4 h-4"></i></span>
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                                
                                {uploading && (
                                    <div className="mt-4">
                                        <div className="w-full bg-slate-200 h-2.5 rounded-full overflow-hidden">
                                            <div 
                                                className="bg-gradient-to-r from-blue-500 to-indigo-600 h-full rounded-full transition-all duration-300"
                                                style={{ width: `${uploadProgress}%` }}
                                            ></div>
                                        </div>
                                        <div className="flex justify-between text-xs text-slate-500 mt-1 font-semibold">
                                            <span>جاري رفع الصورة إلى التخزين الآمن...</span>
                                            <span className="font-poppins">{Math.round(uploadProgress)}%</span>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>

                        <div>
                            <label className="block text-sm font-bold text-slate-700 mb-2">وصف مختصر (يظهر في الكروت)</label>
                            <textarea name="shortDescription" value={formData.shortDescription} onChange={handleChange} rows="3" required className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl focus:border-blue-500 outline-none"></textarea>
                        </div>
                    </>
                )}
                
                {activeTab === 'courses' && (
                    <div className="space-y-4">
                        <div className="flex justify-between items-center mb-4">
                            <p className="text-sm text-slate-500">أضف المواد والخطة الدراسية الخاصة بالبرنامج</p>
                            <Button type="button" onClick={handleAddCourse} icon="plus" variant="secondary" className="py-2 text-sm">إضافة مادة</Button>
                        </div>
                        
                        {loadingDetails ? (
                            <div className="text-center py-8 text-slate-500">جاري التحميل...</div>
                        ) : courses.length === 0 ? (
                            <div className="text-center py-8 bg-slate-50 rounded-xl text-slate-500 border border-dashed border-slate-300">لا توجد مواد دراسية بعد. انقر على "إضافة مادة" للبدء.</div>
                        ) : (
                            courses.map((course, index) => (
                                <div key={course.id} className="bg-slate-50 p-4 rounded-xl border border-slate-200 flex flex-col md:flex-row gap-4 items-start md:items-center relative">
                                    <div className="absolute top-2 left-2 flex gap-2">
                                        <button type="button" onClick={() => handleRemoveCourse(course.id)} className="text-rose-500 hover:bg-rose-100 p-1 rounded-md" title="حذف">
                                            <span className="pointer-events-none"><i data-lucide="trash-2" className="w-4 h-4"></i></span>
                                        </button>
                                    </div>
                                    
                                    <div className="w-full md:w-1/3">
                                        <input type="text" placeholder="اسم المادة عربي" value={course.titleAr} onChange={(e) => handleCourseChange(course.id, 'titleAr', e.target.value)} required className="w-full p-2 text-sm border border-slate-300 rounded-lg outline-none" />
                                    </div>
                                    <div className="w-full md:w-1/3">
                                        <input type="text" placeholder="اسم المادة انجليزي" value={course.titleEn} onChange={(e) => handleCourseChange(course.id, 'titleEn', e.target.value)} className="w-full p-2 text-sm border border-slate-300 rounded-lg outline-none" />
                                    </div>
                                    <div className="w-full md:w-24">
                                        <input type="number" placeholder="الساعات" value={course.creditHours} onChange={(e) => handleCourseChange(course.id, 'creditHours', parseInt(e.target.value))} required className="w-full p-2 text-sm border border-slate-300 rounded-lg outline-none" title="الساعات المعتمدة" />
                                    </div>
                                    <div className="w-full md:w-40">
                                        <select value={course.semester} onChange={(e) => handleCourseChange(course.id, 'semester', e.target.value)} className="w-full p-2 text-sm border border-slate-300 rounded-lg outline-none">
                                            <option value="مقررات إجبارية">مقررات إجبارية</option>
                                            <option value="مقررات اختيارية">مقررات اختيارية</option>
                                            <option value="مقررات استدراكية">مقررات استدراكية</option>
                                        </select>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                )}

                <div className="pt-6 mt-4 border-t border-slate-100 flex gap-4">
                    <Button type="submit" icon="save">حفظ جميع البيانات</Button>
                </div>
            </form>
        </div>
    );
};
