import React, { useState, useEffect, useMemo } from 'react';
import {
LayoutDashboard, Users, Pill, Activity, Search, Plus,
AlertCircle, CheckCircle, FileText, Clock, UserPlus,
Printer, Bone, Trash2, ShieldAlert, ChevronDown, ChevronUp, User,
Droplets
} from 'lucide-react';
// --- ADVANCED MOCK DATA ---
const initialPatients = [
{
id: 1, name: 'John Doe', dob: '1978-05-15', gender: 'Male', weight: 85, height: 178, bloodType: 'O+',
phone: '555-0101', email: 'john@example.com',
allergies: ['Penicillin'],
chronicConditions: ['Hypertension', 'Type 2 Diabetes'],
currentMeds: ['Metformin 500mg']
},
{
id: 2, name: 'Timmy Smith', dob: '2019-08-22', gender: 'Male', weight: 18, height: 110, bloodType: 'A-',
phone: '555-0102', email: 'parent@example.com',
allergies: [],
chronicConditions: ['Asthma'],
currentMeds: ['Albuterol Inhaler']
},
{
id: 3, name: 'Jane Roe', dob: '1945-11-03', gender: 'Female', weight: 62, height: 160, bloodType: 'AB+',
phone: '555-0103', email: 'jane.roe@example.com',
allergies: ['Sulfa Drugs', 'Latex'],
chronicConditions: ['CKD Stage 3', 'Atrial Fibrillation', 'Osteoarthritis'],
currentMeds: ['Warfarin 5mg', 'Amlodipine 5mg']
}
];
// Rich Medication Database with Interaction Mapping
const medicationsDB = [
{ id: 'm1', name: 'Amoxicillin', class: 'Antibiotic (Penicillin)', defaultDose: '500mg', defaultRoute: 'PO', defaultFreq: 'TID', interactsWith: [] },
{ id: 'm2', name: 'Warfarin', class: 'Anticoagulant', defaultDose: '5mg', defaultRoute: 'PO', defaultFreq: 'QD', interactsWith: ['m4', 'm5'] },
{ id: 'm3', name: 'Lisinopril', class: 'ACE Inhibitor', defaultDose: '10mg', defaultRoute: 'PO', defaultFreq: 'QD', interactsWith: ['m4'] },
{ id: 'm4', name: 'Ibuprofen', class: 'NSAID', defaultDose: '400mg', defaultRoute: 'PO', defaultFreq: 'PRN', interactsWith: ['m2', 'm3'] },
{ id: 'm5', name: 'Aspirin', class: 'NSAID / Antiplatelet', defaultDose: '81mg', defaultRoute: 'PO', defaultFreq: 'QD', interactsWith: ['m2'] },
{ id: 'm6', name: 'Azithromycin', class: 'Antibiotic (Macrolide)', defaultDose: '250mg', defaultRoute: 'PO', defaultFreq: 'QD', interactsWith: [] },
{ id: 'm7', name: 'Metformin', class: 'Antidiabetic', defaultDose: '500mg', defaultRoute: 'PO', defaultFreq: 'BID', interactsWith: [] },
{ id: 'm8', name: 'Bactrim', class: 'Antibiotic (Sulfa)', defaultDose: '800/160mg', defaultRoute: 'PO', defaultFreq: 'BID', interactsWith: [] }
];
export default function ClinicMindApp() {
const [currentView, setCurrentView] = useState('dashboard');
const [patients, setPatients] = useState(initialPatients);
const [prescriptions, setPrescriptions] = useState([]);
const [radiologyOrders, setRadiologyOrders] = useState([
{ id: 101, patient: 'Jane Roe', type: 'MRI Brain w/ Contrast', status: 'Resulted', date: '2026-04-04' },
{ id: 102, patient: 'John Doe', type: 'Chest X-Ray PA/Lat', status: 'Pending', date: '2026-04-05' },
{ id: 103, patient: 'Timmy Smith', type: 'Ultrasound Abdomen', status: 'Scheduled', date: '2026-04-06' }
]);
// Helper: Calculate Age from DOB
const getAge = (dob) => {
const today = new Date();
const birthDate = new Date(dob);
let age = today.getFullYear() - birthDate.getFullYear();
const m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) age--;
return age;
};
// --- NAVIGATION COMPONENT ---
const Sidebar = () => (
⚕️ ClinicMindAI
SJ
Dr. Sarah Jenkins
Internal Medicine
);
const NavItem = ({ icon, label, view }) => {
const isActive = currentView === view;
return (
);
};
// --- DASHBOARD VIEW ---
const DashboardView = () => (
Overview Dashboard
Real-time clinical insights and pending tasks.
{new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
} title="Total Patients" value={patients.length} color="blue" />
} title="Pending Rx" value={prescriptions.length} color="purple" />
} title="Imaging Orders" value={radiologyOrders.length} color="amber" />
} title="Dialysis active" value="1" color="teal" />
Recent Clinical Activity
{prescriptions.slice(0, 5).map((rx, idx) => (
{rx.patientName}
{rx.meds.length} medication(s) prescribed
{rx.date}
))}
{prescriptions.length === 0 && (
No recent activity. Start by prescribing a medication.
)}
);
const StatCard = ({ icon, title, value, color }) => {
const colorMap = {
blue: 'bg-blue-50 text-blue-600 border-blue-100',
purple: 'bg-purple-50 text-purple-600 border-purple-100',
amber: 'bg-amber-50 text-amber-600 border-amber-100',
teal: 'bg-teal-50 text-teal-600 border-teal-100'
};
return (
{title}
{React.cloneElement(icon, { size: 18 })}
{value}
);
};
// --- PATIENTS VIEW (Enhanced) ---
const PatientsView = () => {
const [isAdding, setIsAdding] = useState(false);
const [expandedPt, setExpandedPt] = useState(null);
const [newPatient, setNewPatient] = useState({
name: '', dob: '', gender: 'Male', weight: '', height: '', bloodType: 'Unknown', phone: '', allergies: ''
});
const handleAddPatient = (e) => {
e.preventDefault();
const pt = {
...newPatient,
id: Date.now(),
weight: parseFloat(newPatient.weight),
height: parseFloat(newPatient.height),
allergies: newPatient.allergies ? newPatient.allergies.split(',').map(s=>s.trim()) : [],
chronicConditions: [], currentMeds: []
};
setPatients([pt, ...patients]);
setIsAdding(false);
setNewPatient({ name: '', dob: '', gender: 'Male', weight: '', height: '', bloodType: 'Unknown', phone: '', allergies: '' });
};
return (
Patient Directory
{isAdding && (
)}
{patients.map(p => (
{/* Row Header */}
setExpandedPt(expandedPt === p.id ? null : p.id)}
>
{p.name.split(' ').map(n=>n[0]).join('')}
{p.name}
ID: PT-{10000 + p.id}
{getAge(p.dob)} yrs • {p.gender}
DOB: {p.dob}
{p.allergies.length > 0 ? (
{p.allergies.length} Allergies
) : NKA}
{expandedPt === p.id ? : }
{/* Expanded Details */}
{expandedPt === p.id && (
Vitals & Demographics
Weight: {p.weight} kg
Height: {p.height} cm
BMI: {((p.weight / ((p.height/100)**2)) || 0).toFixed(1)}
Blood: {p.bloodType}
Allergies
{p.allergies.length > 0 ? (
{p.allergies.map(a => - {a}
)}
) :
No Known Allergies (NKA)
}
Chronic Conditions
{p.chronicConditions.length > 0 ? (
{p.chronicConditions.map(c => {c})}
) :
None recorded
}
)}
))}
);
};
// --- ADVANCED e-PRESCRIPTION (Rx) MODULE ---
const PrescriptionView = () => {
const [selectedPatientId, setSelectedPatientId] = useState('');
// Dynamic array for multiple drugs
const [rxList, setRxList] = useState([{ id: Date.now(), medId: '', dose: '', route: 'PO', freq: 'QD', duration: '7 days', disp: '' }]);
const [aiStatus, setAiStatus] = useState('idle');
const [aiMessages, setAiMessages] = useState([]); // Array of { type: 'danger'|'warning'|'safe', msg }
const activePatient = patients.find(p => p.id === parseInt(selectedPatientId));
// When patient changes or rxList changes, reset AI status
useEffect(() => { setAiStatus('idle'); setAiMessages([]); }, [selectedPatientId, rxList]);
const addMedRow = () => {
setRxList([...rxList, { id: Date.now(), medId: '', dose: '', route: 'PO', freq: 'QD', duration: '7 days', disp: '' }]);
};
const removeMedRow = (id) => {
if(rxList.length > 1) {
setRxList(rxList.filter(row => row.id !== id));
}
};
const updateMedRow = (id, field, value) => {
setRxList(rxList.map(row => {
if (row.id === id) {
const newRow = { ...row, [field]: value };
// Auto-populate defaults if med changes
if (field === 'medId' && value !== '') {
const medDef = medicationsDB.find(m => m.id === value);
if(medDef) {
newRow.dose = medDef.defaultDose;
newRow.route = medDef.defaultRoute;
newRow.freq = medDef.defaultFreq;
}
}
return newRow;
}
return row;
}));
};
const runAdvancedAiCheck = () => {
if (!activePatient) { alert("Select a patient first."); return; }
const selectedMeds = rxList.filter(row => row.medId !== '').map(row => medicationsDB.find(m => m.id === row.medId));
if (selectedMeds.length === 0) { alert("Add at least one medication."); return; }
setAiStatus('analyzing');
setAiMessages([]);
setTimeout(() => {
let messages = [];
let hasDanger = false;
let hasWarning = false;
const patientAge = getAge(activePatient.dob);
// 1. ALLERGY CHECK
selectedMeds.forEach(med => {
// Simplistic mock allergy check logic (string match class/name)
const isAllergic = activePatient.allergies.some(alg =>
med.class.toLowerCase().includes(alg.toLowerCase()) ||
med.name.toLowerCase().includes(alg.toLowerCase())
);
if (isAllergic) {
hasDanger = true;
messages.push({ type: 'danger', title: 'Allergy Conflict', msg: `Patient has documented allergy matching ${med.name} (${med.class}). ABSOLUTE CONTRAINDICATION.` });
}
});
// 2. DRUG-DRUG INTERACTION CHECK (O(N^2) pairing)
for (let i = 0; i < selectedMeds.length; i++) {
for (let j = i + 1; j < selectedMeds.length; j++) {
const m1 = selectedMeds[i];
const m2 = selectedMeds[j];
if (m1.interactsWith.includes(m2.id) || m2.interactsWith.includes(m1.id)) {
hasDanger = true;
messages.push({ type: 'danger', title: 'Severe Interaction', msg: `${m1.name} + ${m2.name}: High risk of adverse reaction. Concurrent use requires strict monitoring.` });
}
}
}
// 3. PEDIATRIC DOSAGE CHECK
if (patientAge < 12) {
selectedMeds.forEach(med => {
// Find specific row for this med to check dose
const row = rxList.find(r => r.medId === med.id);
if (row && row.dose.includes('500mg') && med.name === 'Amoxicillin') {
hasWarning = true;
messages.push({ type: 'warning', title: 'Pediatric Dosage', msg: `${med.name} 500mg exceeds standard weight-based dosing for a ${patientAge}-yr-old (${activePatient.weight}kg). Consider 250mg.` });
}
});
}
// Generate Status
if (messages.length === 0) {
setAiStatus('safe');
setAiMessages([{ type: 'safe', title: 'All Clear', msg: 'No allergies or drug-drug interactions detected. Dosages appear appropriate.' }]);
} else {
setAiStatus(hasDanger ? 'danger' : 'warning');
setAiMessages(messages);
}
}, 1200);
};
const handleSign = () => {
if(aiStatus === 'idle' || aiStatus === 'analyzing') { alert("Run AI Check First."); return; }
const prescribedDrugs = rxList.filter(r => r.medId !== '').map(r => {
const name = medicationsDB.find(m => m.id === r.medId)?.name;
return `${name} ${r.dose} ${r.route} ${r.freq}`;
});
const newRx = { patientName: activePatient.name, meds: prescribedDrugs, date: new Date().toLocaleDateString() };
setPrescriptions([newRx, ...prescriptions]);
alert("Prescription digitally signed & sent to pharmacy/patient portal.");
// Reset
setRxList([{ id: Date.now(), medId: '', dose: '', route: 'PO', freq: 'QD', duration: '7 days', disp: '' }]);
setSelectedPatientId('');
};
return (
Smart e-Prescription Engine
Build complex regimens with real-time multi-drug safety guardrails.
{/* LEFT: Rx Builder (Takes 2 columns on extra large screens) */}
{/* Patient Selector */}
{activePatient && (
Wt: {activePatient.weight}kg
{activePatient.allergies.length} Allergies
)}
{/* Dynamic Drug List */}
Medication Regimen
Rx Draft
{rxList.map((row, index) => (
{/* Delete Button */}
{rxList.length > 1 && (
)}
{/* Drug Name */}
{/* Dose */}
updateMedRow(row.id, 'dose', e.target.value)} placeholder="e.g. 500mg" className="w-full p-2 border border-slate-300 rounded-md outline-none focus:border-teal-500" disabled={!row.medId}/>
{/* Route */}
{/* Frequency */}
{/* Duration */}
updateMedRow(row.id, 'duration', e.target.value)} placeholder="e.g. 7 days" className="w-full p-2 border border-slate-300 rounded-md outline-none focus:border-teal-500" disabled={!row.medId}/>
))}
{/* RIGHT: AI Safety Engine & Actions */}
{/* AI Output Console */}
Safety Report
{aiStatus === 'idle' && (
Build your prescription and run the scan to detect conflicts.
)}
{aiStatus === 'analyzing' && (
Analyzing Medical Knowledge Graph...
Cross-referencing {rxList.length} drug(s) with patient history.
)}
{(aiStatus === 'safe' || aiStatus === 'warning' || aiStatus === 'danger') && (
{aiMessages.map((msg, i) => (
{msg.type === 'danger' &&
}
{msg.type === 'warning' && }
{msg.type === 'safe' && }
{msg.title}
{msg.msg}
))}
)}
{/* Action Area Footer */}
);
};
// --- MINOR MODULES: RADIOLOGY & LABS ---
const RadiologyView = () => {
const [newOrder, setNewOrder] = useState({ patientId: '', type: 'X-Ray', detail: '', indication: '' });
const handleSubmit = (e) => {
e.preventDefault();
if(!newOrder.patientId) return alert('Please select a patient.');
const patient = patients.find(p => p.id === parseInt(newOrder.patientId));
setRadiologyOrders([{
id: Date.now(),
patient: patient.name,
type: `${newOrder.type} - ${newOrder.detail || 'General'}`,
status: 'Pending',
date: new Date().toLocaleDateString()
}, ...radiologyOrders]);
setNewOrder({ patientId: '', type: 'X-Ray', detail: '', indication: '' });
alert('Diagnostic order submitted successfully.');
};
return (
Radiology & Labs
Order diagnostics and track results in real-time.
{/* Form */}
{/* Queue */}
Imaging Queue
{radiologyOrders.length} Total
{radiologyOrders.map(order => (
{order.type}
Patient: {order.patient} • Ordered: {order.date}
{order.status}
))}
{radiologyOrders.length === 0 &&
No imaging orders in the queue.
}
);
};
// --- MINOR MODULES: DIALYSIS UNIT ---
const DialysisView = () => {
return (
Dialysis Unit Management
Real-time monitoring of active dialysis stations and maintenance tracking.
{/* Active Station Card */}
Session Progress
1h 45m left
{/* Maintenance Station Card */}
Sterilization cycle in progress...
{/* Empty Station Card */}
Assign Patient
Station B-01 is available
);
}
// --- MAIN RENDER ---
return (
{/* Top subtle fade effect */}
{currentView === 'dashboard' &&
}
{currentView === 'patients' &&
}
{currentView === 'rx' &&
}
{currentView === 'radio' &&
}
{currentView === 'dialysis' &&
}
{/* Global Style overrides for scrollbars within this component scope */}
);
}