import React, { useState, useEffect } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken } from 'firebase/auth';
import { getFirestore, collection, doc, setDoc, getDoc, onSnapshot, query, addDoc, updateDoc, deleteDoc, arrayUnion } from 'firebase/firestore';
import {
Plus, Users, ClipboardList, Activity, TestTube, Image as ImageIcon,
Search, ChevronRight, Save, Trash2, ArrowRight, UserPlus, Clock,
FileText, Menu, X, LogOut, Camera, Ruler, Weight, Stethoscope, ListChecks, Lock, Key, ShieldCheck, FileDown, Eye
} from 'lucide-react';
// --- إعدادات النظام السحابي ---
const firebaseConfig = JSON.parse(__firebase_config);
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const appId = typeof __app_id !== 'undefined' ? __app_id : 'hostinger-med-app';
// --- مكونات واجهة المستخدم ---
const Card = ({ children, className = "" }) => (
{children}
);
const Input = ({ label, ...props }) => (
{label && }
);
const Select = ({ label, options, ...props }) => (
{label && }
);
const TextArea = ({ label, ...props }) => (
{label && }
);
// --- التطبيق الرئيسي ---
export default function App() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [activeTab, setActiveTab] = useState('list');
const [patients, setPatients] = useState([]);
const [selectedPatientId, setSelectedPatientId] = useState(null);
const [searchQuery, setSearchQuery] = useState("");
const [isSidebarOpen, setSidebarOpen] = useState(false);
const [passInput, setPassInput] = useState("");
const [loginError, setLoginError] = useState(false);
const APP_PASSWORD = "1234";
useEffect(() => {
const initAuth = async () => {
try {
if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) {
await signInWithCustomToken(auth, __initial_auth_token);
} else {
await signInAnonymously(auth);
}
} catch (err) {
console.error("Connection error:", err);
}
};
initAuth();
const unsubscribe = onAuthStateChanged(auth, (u) => {
setUser(u);
setLoading(false);
});
return () => unsubscribe();
}, []);
useEffect(() => {
if (!user || !isAuthenticated) return;
const q = collection(db, 'artifacts', appId, 'users', user.uid, 'patients');
const unsubscribe = onSnapshot(q, (snapshot) => {
const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
setPatients(data);
}, (err) => console.error("Data fetch error:", err));
return () => unsubscribe();
}, [user, isAuthenticated]);
const handleLogin = (e) => {
e.preventDefault();
if (passInput === APP_PASSWORD) {
setIsAuthenticated(true);
setLoginError(false);
} else {
setLoginError(true);
setPassInput("");
}
};
const handleAddPatient = async (patientData) => {
if (!user) return;
try {
const docRef = await addDoc(collection(db, 'artifacts', appId, 'users', user.uid, 'patients'), {
...patientData,
createdAt: new Date().toISOString(),
vitals: [],
labs: [],
images: [],
recommendations: "",
exam_notes: ""
});
setSelectedPatientId(docRef.id);
setActiveTab('details');
} catch (err) {
console.error("Save error:", err);
}
};
const selectedPatient = patients.find(p => p.id === selectedPatientId);
if (loading) return (
);
if (!isAuthenticated) {
return (
سجلاتي الطبية
نظام المتابعة الخاص والمؤمن
);
}
return (
{/* Sidebar Responsive */}
{/* Header */}
{/* Dynamic Content */}
{activeTab === 'list' && (
{patients.filter(p => p.name.includes(searchQuery)).map(p => (
{ setSelectedPatientId(p.id); setActiveTab('details'); }} className="p-5 md:p-6">
{p.name.charAt(0)}
{p.age} Y
{p.name}
{p.reason || 'لا يوجد سبب قبول'}
{p.vitals?.length || 0} متابعة
))}
{patients.length === 0 &&
لا يوجد بيانات حالياً
}
)}
{activeTab === 'add' &&
}
{activeTab === 'details' && selectedPatient && (
{
await updateDoc(doc(db, 'artifacts', appId, 'users', user.uid, 'patients', selectedPatient.id), updates);
}}
onDelete={async () => {
if (window.confirm("حذف ملف المريض نهائياً؟")) {
await deleteDoc(doc(db, 'artifacts', appId, 'users', user.uid, 'patients', selectedPatient.id));
setActiveTab('list');
}
}}
/>
)}
{isSidebarOpen &&
setSidebarOpen(false)} className="fixed inset-0 bg-slate-900/40 z-30 md:hidden backdrop-blur-sm transition-opacity">
}
);
}
// --- نموذج إضافة مريض جديد ---
function PatientAddForm({ onSave }) {
const [data, setData] = useState({
name: "", age: "", gender: "", maritalStatus: "",
job: "", companion: "", reason: "",
height: "", weight: "",
surgical_history: "", drug_history: "", medical_history: "",
family_history: "", allergy_history: "", smoking: "",
complaint_details: "",
procedures_initial: "",
exam_head: "", exam_chest: "", exam_heart: "", exam_abdomen: "", exam_limbs: "", exam_neuro: ""
});
return (
المعلومات الأساسية
setData({...data, name: e.target.value})} />
setData({...data, age: e.target.value})} />
setData({...data, height: e.target.value})} />
setData({...data, weight: e.target.value})} />
setData({...data, reason: e.target.value})} />
);
}
// --- شاشة عرض التفاصيل والأرشيف المتعدد ---
function PatientDetailsView({ patient, onUpdate, onDelete }) {
const [subTab, setSubTab] = useState('vitals');
const [isAddingVital, setIsAddingVital] = useState(false);
const [isAddingLab, setIsAddingLab] = useState(false);
const [newVital, setNewVital] = useState({ time: "8 صباحاً", hr: "", bp: "", sat: "", t: "", rr: "", uop: "", glu: "", note: "" });
const labKeys = ["WBC", "N/L", "HGB", "MCV", "PLT", "GLU", "ALBU", "K", "NA", "CL", "I.Ca", "UR", "CR", "CRP"];
const [newLab, setNewLab] = useState({ date: new Date().toLocaleDateString('en-GB') });
const handleAddVital = () => {
onUpdate({ vitals: arrayUnion({ ...newVital, timestamp: new Date().toISOString() }) });
setIsAddingVital(false);
setNewVital({ time: "8 صباحاً", hr: "", bp: "", sat: "", t: "", rr: "", uop: "", glu: "", note: "" });
};
const handleAddLab = () => {
onUpdate({ labs: arrayUnion({ ...newLab, timestamp: new Date().toISOString() }) });
setIsAddingLab(false);
setNewLab({ date: new Date().toLocaleDateString('en-GB') });
};
const handleFileUpload = (e) => {
const file = e.target.files[0];
if (file) {
// تم حذف شرط الحجم (file.size) بناءً على طلب المستخدم
const reader = new FileReader();
reader.onloadend = () => {
onUpdate({
images: arrayUnion({
data: reader.result,
type: file.type,
title: prompt("عنوان التقرير أو الأشعة:") || "تقرير طبي",
date: new Date().toISOString()
})
});
};
reader.readAsDataURL(file);
}
};
return (
{/* Tabs Responsive Scrollable on Mobile */}
{[
{id: 'summary', label: 'السيرة', icon: FileText},
{id: 'vitals', label: 'المتابعة', icon: Activity},
{id: 'labs', label: 'التحاليل', icon: TestTube},
{id: 'images', label: 'الأرشيف', icon: ImageIcon},
{id: 'notes', label: 'هامش', icon: ClipboardList},
].map(t => (
))}
{subTab === 'summary' && (
الإجراءات الأولية
بيانات المريض
الاسم: {patient.name}
العمر/الجنس: {patient.age} / {patient.gender === 'male' ? 'ذكر' : 'أنثى'}
الحالة: {patient.maritalStatus || '-'}
الوزن/الطول: {patient.weight || '-'} / {patient.height || '-'}
الشكاية: {patient.reason}
السوابق المرضية
مرضية: {patient.medical_history || 'لا يوجد'}
جراحية: {patient.surgical_history || 'لا يوجد'}
)}
{subTab === 'vitals' && (
متابعة العلامات الحيوية
| TIME |
HR | BP |
SAT | T |
RR | UOP |
GLU | ملاحظات |
{patient.vitals?.sort((a,b) => b.timestamp.localeCompare(a.timestamp)).map((v, i) => (
| {v.time} |
{v.hr} | {v.bp} |
{v.sat} | {v.t} |
{v.rr} | {v.uop} |
{v.glu} | {v.note} |
))}
التوصيات الطبية اليومية
)}
{subTab === 'labs' && (
أرشيف التحاليل المخبرية
| التاريخ |
{labKeys.map(k => {k} | )}
{patient.labs?.map((l, i) => (
| {l.date} |
{labKeys.map(k => {l[k] || '-'} | )}
))}
)}
{subTab === 'images' && (
رفع مرفقات (صورة أشعة / إيكو / تقرير PDF)
يدعم كافة صيغ الصور و مستندات الـ PDF
{patient.images?.map((img, i) => (
{img.type === 'application/pdf' ? (
مستند PDF
) : (

)}
{img.title}
{new Date(img.date).toLocaleDateString()}
))}
)}
{subTab === 'notes' && (
هامش الإضافة والتعديل
)}
{/* مودال المتابعة */}
{isAddingVital && (
متابعة جديدة
setNewVital({...newVital, time: e.target.value})} options={[{label:"8 صباحاً", value:"8 صباحاً"},{label:"12 ظهراً", value:"12 ظهراً"},{label:"6 مساءً", value:"6 مساءً"},{label:"12 ليلاً", value:"12 ليلاً"},{label:"6 صباحاً", value:"6 صباحاً"}]} />
setNewVital({...newVital, hr: e.target.value})} />
setNewVital({...newVital, bp: e.target.value})} />
setNewVital({...newVital, sat: e.target.value})} />
setNewVital({...newVital, t: e.target.value})} />
setNewVital({...newVital, rr: e.target.value})} />
setNewVital({...newVital, uop: e.target.value})} />
setNewVital({...newVital, glu: e.target.value})} />
)}
{/* مودال التحاليل */}
{isAddingLab && (
)}
);
}