import React, { useState, useEffect, useRef } from "react"; import { doc, getDoc, setDoc } from "firebase/firestore"; import { db, auth } from "../firebase"; import { FileText, Save, Check, RefreshCw, AlertTriangle, ChevronRight, ChevronLeft, Sparkles, BookOpen } from "lucide-react"; interface LessonNotesSidebarProps { lesson: { docId?: string; id: string | number; title: string; }; playBeep?: (type: string) => void; } export const LessonNotesSidebar: React.FC = ({ lesson, playBeep }) => { const [content, setContent] = useState(""); const [notesId, setNotesId] = useState(""); const [isCollapsed, setIsCollapsed] = useState(false); // Status states const [loading, setLoading] = useState(false); const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle"); const [errorMsg, setErrorMsg] = useState(null); const [lastSavedTime, setLastSavedTime] = useState(null); const user = auth.currentUser; const timeoutRef = useRef(null); // Generate unique notes document ID for Firebase: userId + lessonId const getNoteDocId = () => { if (!user) return ""; const cleanLessonId = String(lesson.docId || lesson.id).replace(/[^a-zA-Z0-9_\-]/g, ""); return `${user.uid}_${cleanLessonId}`; }; // Load existing note on mount or when user/lesson changes useEffect(() => { if (!user) { setContent(""); setSaveStatus("idle"); return; } const docId = getNoteDocId(); setNotesId(docId); setLoading(true); setSaveStatus("idle"); setErrorMsg(null); const fetchNote = async () => { try { const noteRef = doc(db, "lesson_notes", docId); const noteDoc = await getDoc(noteRef); if (noteDoc.exists()) { const data = noteDoc.data(); setContent(data.content || ""); if (data.updatedAt) { const date = new Date(data.updatedAt); setLastSavedTime(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })); setSaveStatus("saved"); } } else { setContent(""); setLastSavedTime(null); } } catch (err: any) { console.error("Eslatmani yuklashda xatolik:", err); setErrorMsg("Eslatmani yuklab bo'lmadi."); setSaveStatus("error"); } finally { setLoading(false); } }; fetchNote(); }, [lesson.id, lesson.docId, user?.uid]); // Handle manual saving const handleSave = async (textToSave = content) => { if (!user) { setErrorMsg("Eslatmalarni saqlash uchun tizimga kirishingiz lozim."); setSaveStatus("error"); if (playBeep) playBeep("error"); return; } const docId = getNoteDocId() || notesId; if (!docId) return; setSaveStatus("saving"); setErrorMsg(null); try { const noteRef = doc(db, "lesson_notes", docId); const now = Date.now(); await setDoc(noteRef, { id: docId, userId: user.uid, lessonId: String(lesson.docId || lesson.id), lessonTitle: lesson.title, content: textToSave, updatedAt: now }, { merge: true }); const date = new Date(now); setLastSavedTime(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })); setSaveStatus("saved"); if (playBeep) playBeep("levelUp"); } catch (err: any) { console.error("Eslatmani saqlashda xatolik:", err); setErrorMsg("Internet ulanishi yoki ruxsat yo'q."); setSaveStatus("error"); if (playBeep) playBeep("error"); } }; // Debounced auto-save on typing if logged in const handleTextChange = (e: React.ChangeEvent) => { const text = e.target.value; setContent(text); setSaveStatus("idle"); if (!user) return; // Clear previous timeout if (timeoutRef.current) { clearTimeout(timeoutRef.current); } // Set new timeout for auto-saving after 1.5s of idle typing timeoutRef.current = setTimeout(() => { handleSave(text); }, 1500); }; // Cleanup timeout on unmount useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, []); const charCount = content.length; const wordCount = content.trim() ? content.trim().split(/\s+/).length : 0; // Render Collapsed trigger vertical tab if (isCollapsed) { return ( ); } return (
{/* Drawer Header */}

Dars eslatmasi

Shaxsiy konspektlaringiz

{/* Editor Body */}
{/* Loading Indicator Overlay */} {loading ? (
Eslatmalarni yuklanmoqda...
) : (