You are an expert AI assistant tasked with generating a complete, production-ready, single-page React application using Next.js and Tailwind CSS. The application is a Personal Health Data Management Platform, inspired by the need for patients to take control of their medical information as highlighted in a Hacker News post about a founder battling cancer. The goal is to provide a secure, user-friendly interface for individuals to store, organize, share, and analyze their health data.
**1. PROJECT OVERVIEW:**
- **Purpose:** To empower patients by providing a centralized, secure platform for managing their comprehensive health records. This includes diagnostics, treatment history, medications, and doctor's notes.
- **Problem Solved:** The current healthcare system often fragments patient data across different providers, making it difficult for patients to have a complete overview of their health. Patients, especially those with complex or chronic conditions, need a unified and accessible way to manage their information, facilitate communication with healthcare professionals, and potentially contribute to medical research.
- **Value Proposition:** "Take control of your health narrative. Securely manage, understand, and share your medical data with confidence." The platform offers peace of mind, improved doctor-patient communication, and a foundation for personalized treatment.
**2. TECH STACK:**
- **Framework:** Next.js (for SSR/SSG capabilities, API routes, and overall performance)
- **UI Library:** React
- **Styling:** Tailwind CSS (for rapid UI development and utility-first styling)
- **State Management:** Zustand (lightweight and efficient for global state management)
- **Forms:** React Hook Form (for robust form handling and validation)
- **Icons:** Heroicons (or similar for clean, scalable icons)
- **Date Handling:** date-fns (for reliable date manipulation)
- **Data Fetching:** Next.js built-in fetch or SWR/React Query (if more complex caching/revalidation is needed later)
- **Local Storage:** Standard browser localStorage API for persisting user preferences or session data.
- **Deployment:** Vercel (optimized for Next.js)
**3. CORE FEATURES:**
- **User Authentication:** Secure sign-up, login, and logout using NextAuth.js or a similar robust solution. Implement password reset functionality.
- **Dashboard:** A central hub displaying a summary of the user's health status. This includes key vitals (if entered), upcoming appointments, recent documents, and quick links to add new data.
- **Data Management (Upload & Organize):**
- **File Upload:** Allow users to upload various medical documents (PDFs, images like X-rays/MRIs, text files). Use a secure cloud storage solution like AWS S3 or Google Cloud Storage (for MVP, could simulate with local storage or a placeholder service).
- **Data Categorization:** Users can categorize uploads (e.g., 'Diagnoses', 'Lab Results', 'Prescriptions', 'Treatment Plans', 'Doctor's Notes', 'Imaging').
- **Structured Data Entry:** Forms for entering specific data points like vital signs, medication details (name, dosage, frequency), allergies, and diagnoses (with date and notes).
- **Secure Sharing:**
- **Grant Access:** Users can select specific documents or data categories to share with designated individuals (e.g., doctors, family members) via secure, time-limited, or revocable links.
- **Access Control:** Implement logic to ensure only authorized users can view shared data.
- **Notes & Reminders:**
- **Clinical Notes:** A rich text editor for users to jot down observations, symptoms, or questions for their doctor.
- **Appointment Reminders:** Functionality to set reminders for upcoming appointments, medication refills, or follow-up tests.
**User Flows:**
1. **Onboarding:** User signs up -> Completes basic profile -> Lands on Dashboard.
2. **Uploading a Report:** User clicks 'Upload Document' -> Selects file -> Chooses category (e.g., 'Lab Results') -> Adds optional notes -> Clicks 'Save'. File appears in the document list and relevant section.
3. **Entering Vitals:** User navigates to 'Vitals' -> Clicks 'Add New' -> Fills form (Date, Systolic, Diastolic, Pulse) -> Clicks 'Save'. Data is added to the vitals chart/table.
4. **Sharing Data:** User selects a document -> Clicks 'Share' -> Enters email of recipient or generates a shareable link -> Sets expiry (optional) -> Clicks 'Confirm'.
**4. UI/UX DESIGN:**
- **Layout:** Single Page Application (SPA) structure. Main navigation sidebar (collapsible on smaller screens) with links to Dashboard, Documents, Vitals, Medications, Notes, Sharing, Settings. Main content area displays the selected section.
- **Color Palette:** Calming and professional. Primary: A soft blue (#4A90E2). Secondary: A light grey (#F5F7FA) for backgrounds. Accent: A subtle green (#50E3C2) for success states and key actions. Text: Dark grey (#333333). Use error states (e.g., red) sparingly.
- **Typography:** Clean and readable sans-serif font. Headings: Inter (bold). Body text: Inter (regular). Ensure good line height and spacing.
- **Responsive Design:** Mobile-first approach. Sidebar collapses into a hamburger menu on small screens. Content adjusts fluidly. Use Tailwind CSS's responsive prefixes (sm:, md:, lg:).
- **Interactivity:** Subtle hover effects on buttons and links. Smooth transitions for panel expansions and modal appearances. Clear loading indicators.
**5. COMPONENT BREAKDOWN:**
- **`Layout.js`:** Main app shell. Includes Header, Sidebar, and main content area. Handles responsive navigation.
- Props: `children` (the page content).
- **`Header.js`:** Top navigation bar. Includes app logo, user profile dropdown, notifications.
- Props: `user` (user object).
- **`Sidebar.js`:** Collapsible navigation menu. Contains links to different app sections.
- Props: `isOpen` (boolean), `onClose` (function).
- **`Dashboard.js`:** Displays summary widgets.
- Props: `userData` (summary data).
- Sub-components: `StatsWidget.js`, `RecentDocsWidget.js`, `UpcomingAppointmentsWidget.js`.
- **`DocumentList.js`:** Displays uploaded documents in a table or grid.
- Props: `documents` (array), `onView` (function), `onShare` (function), `onDelete` (function).
- **`FileUpload.js`:** Component for handling file uploads.
- Props: `onUploadSuccess` (function), `categoryId` (string).
- **`DataEntryForm.js`:** Generic form component for structured data (Vitals, Meds, etc.).
- Props: `fields` (array of form field configs), `onSubmit` (function), `initialData` (object).
- **`ShareModal.js`:** Modal for configuring data sharing.
- Props: `documentId` (string), `onShare` (function).
- **`NotesEditor.js`:** Rich text editor for clinical notes.
- Props: `initialValue` (string), `onChange` (function).
- **`ReminderManager.js`:** Component for setting and viewing reminders.
- Props: `reminders` (array), `onAddReminder` (function).
**6. DATA MODEL & STATE MANAGEMENT:**
- **Global State (Zustand Store):**
- `user`: { id, name, email, profilePic }
- `documents`: [ { id, name, url, category, uploadDate, notes } ]
- `vitals`: [ { id, date, systolic, diastolic, pulse } ]
- `medications`: [ { id, name, dosage, frequency, startDate, endDate } ]
- `diagnoses`: [ { id, name, date, notes } ]
- `appointments`: [ { id, date, time, location, notes } ]
- `reminders`: [ { id, date, message, type } ]
- `sharingSettings`: { documentId: [userIds or shareLinks] }
- `ui`: { isLoading, error, notifications }
- **Mock Data Format (Example for Documents):**
```json
[
{
"id": "doc_123abc",
"name": "Complete Blood Count - 2023-10-26.pdf",
"url": "/api/files/doc_123abc", // Placeholder for actual URL
"category": "Lab Results",
"uploadDate": "2023-10-26T10:30:00Z",
"notes": "Standard blood work before next treatment phase."
},
{
"id": "doc_456def",
"name": "MRI Scan - Lumbar Spine.jpg",
"url": "/api/files/doc_456def",
"category": "Imaging",
"uploadDate": "2023-10-20T14:00:00Z",
"notes": "Shows progression in T5 vertebrae."
}
]
```
- **Mock Data Format (Example for Vitals):**
```json
[
{
"id": "vital_789ghi",
"date": "2023-10-27T08:00:00Z",
"systolic": 125,
"diastolic": 80,
"pulse": 72
}
]
```
- **API Routes (Next.js):** Basic routes for handling CRUD operations for each data type (e.g., `/api/documents`, `/api/vitals`). Simulate API calls for MVP if no backend is available.
**7. ANIMATIONS & INTERACTIONS:**
- **Hover Effects:** Subtle background color change or slight shadow lift on interactive elements (buttons, cards, list items).
- **Transitions:** Smooth fade-in/out for modals and dropdowns. Slide-in animation for the sidebar on mobile. Page transition animations (e.g., fade) using Next.js `Layout Shift` or similar techniques.
- **Loading States:** Use spinners or skeleton loaders when data is being fetched or processed. Disable buttons during submission.
- **Micro-interactions:** Visual feedback on successful save (e.g., a brief checkmark animation), error messages appearing smoothly.
**8. EDGE CASES:**
- **Empty States:** Display informative messages and clear calls to action when lists are empty (e.g., "No documents uploaded yet. Click 'Upload' to add your first report.").
- **Error Handling:** Gracefully handle API errors (network issues, server errors). Display user-friendly error messages. Implement form validation (required fields, valid formats) using React Hook Form.
- **Validation:** Client-side and server-side validation for all form inputs. Specific validation for dates, numerical values (e.g., blood pressure ranges).
- **Accessibility (a11y):** Use semantic HTML. Ensure proper ARIA attributes for dynamic content and interactive elements. Keyboard navigability. Sufficient color contrast. Alt text for images.
- **Security:** Implement rate limiting on API routes. Sanitize all user inputs. Use secure authentication practices. Be mindful of HIPAA compliance considerations if handling sensitive health data in a production environment (though MVP might abstract this).
**9. SAMPLE DATA (Mock):**
- **Documents:**
```json
[
{"id": "doc_a1", "name": "Annual Physical Report 2023.pdf", "category": "Check-ups", "uploadDate": "2023-01-15T09:00:00Z", "notes": "Routine annual checkup, all vitals stable.", "url": "/placeholder/doc_a1.pdf"},
{"id": "doc_a2", "name": "MRI Thoracic Spine.png", "category": "Imaging", "uploadDate": "2023-05-20T11:30:00Z", "notes": "Follow-up scan as discussed.", "url": "/placeholder/doc_a2.png"},
{"id": "doc_a3", "name": "Metformin Prescription.jpg", "category": "Prescriptions", "uploadDate": "2023-03-10T16:45:00Z", "notes": "New prescription for blood sugar management.", "url": "/placeholder/doc_a3.jpg"}
]
```
- **Vitals:**
```json
[
{"id": "v_a1", "date": "2023-10-26T08:00:00Z", "systolic": 130, "diastolic": 85, "pulse": 70},
{"id": "v_a2", "date": "2023-07-15T09:00:00Z", "systolic": 128, "diastolic": 82, "pulse": 68}
]
```
- **Medications:**
```json
[
{"id": "med_a1", "name": "Metformin 500mg", "dosage": "500mg", "frequency": "Twice daily", "startDate": "2023-03-10", "endDate": null},
{"id": "med_a2", "name": "Lisinopril 10mg", "dosage": "10mg", "frequency": "Once daily", "startDate": "2022-11-01", "endDate": null}
]
```
- **Diagnoses:**
```json
[
{"id": "diag_a1", "name": "Hypertension", "date": "2022-11-01", "notes": "Controlled with medication.", "url": null},
{"id": "diag_a2", "name": "Osteosarcoma", "date": "2023-05-01", "notes": "T5 vertebrae, undergoing treatment.", "url": null}
]
```
- **Appointments:**
```json
[
{"id": "app_a1", "date": "2023-11-15T14:00:00Z", "location": "Oncology Dept.", "notes": "Post-treatment review.", "url": null},
{"id": "app_a2", "date": "2023-12-01T10:00:00Z", "location": "Dr. Smith's Office", "notes": "Follow-up on blood work.", "url": null}
]
```
**10. DEPLOYMENT NOTES:**
- **Build:** Run `npm run build` or `yarn build`.
- **Environment Variables:** Use a `.env.local` file for local development (e.g., `NEXTAUTH_URL`, `NEXTAUTH_SECRET`, `DATABASE_URL` if using a real DB later, `CLOUD_STORAGE_BUCKET`). Ensure these are correctly set in the Vercel deployment environment.
- **Performance Optimizations:** Utilize Next.js image optimization. Code splitting will be handled automatically by Next.js. Optimize Tailwind CSS by purging unused styles in production builds. Lazy load components where appropriate.
- **API Routes:** For MVP, mock API responses directly within the API routes or use a simple in-memory store. For production, integrate with a database (e.g., PostgreSQL with Prisma) and a cloud storage provider (AWS S3, Google Cloud Storage).
- **HTTPS:** Ensure deployment uses HTTPS.
- **CORS:** Configure CORS appropriately if the frontend and backend are on different domains (though Next.js API routes usually handle this implicitly within the same project).