# Medklinix Platform - Client

Web-based clinical management platform SaaS with professional landing page, robust internal dashboard, authentication system, and internationalization support.

## Requirements

- **Patient Record**: Store personal data, complete medical history, test results, physical exam results, vital signs, diagnosis, and treatment plan
- **Individual Patient Page**: Display patient's record, consultation history, prescriptions, and attached exams (JPG or PDF)
- **Appointment Calendar**: Daily schedule with list of patients per day and automatic confirmations via WhatsApp, SMS, and email
- **Customizable medical or dental record** with interactive 2D/3D graphical odontogram
- **Customizable prescription forms** with digital signature, doctor's logo, ICD-10 and dental CDT diagnoses
- **Advanced search engine** that filters patients by name, dates, or diagnoses
- **Payment gateway** for subscription plans (monthly, semi-annual, annual) integrated with PayPal and Stripe

---

## Tech Stack

- **Framework**: Next.js 14+
- **Language**: TypeScript
- **UI Library**: shadcn/ui (21+ components)
- **Styling**: Tailwind CSS v4
- **Icons**: Lucide Icons
- **State Management**: React Context (Authentication, Language)
- **Form Validation**: Zod
- **HTTP Client**: Axios

---

## 🔐 Authentication System

### Features
- User registration with email
- Login with email and password
- Password reset functionality
- User types: Patient, Doctor, Staff, Admin
- JWT token-based authentication
- Profile management
- Auto-logout on token expiration

### Auth Pages
- **Login**: `/login` - Email and password authentication
- **Register**: `/register` - Create new user account with user type selection
- **Forgot Password**: `/forgot-password` - Two-step password recovery
- **Profile**: `/dashboard/profile` - View and update user profile

### Auth Services
Located at: `lib/auth-service.ts`
- `register()` - Register new user
- `login()` - Login user
- `forgotPassword()` - Request password reset
- `resetPassword()` - Reset password with token
- `verify()` - Verify JWT token
- `logout()` - Clear stored credentials
- `getToken()` - Get stored JWT token
- `getUser()` - Get stored user data
- `isAuthenticated()` - Check if user is logged in

### Auth Schemas
Located at: `lib/auth-schemas.ts`
- Login form validation
- Registration form validation
- Forgot password form validation
- Reset password form validation

---

## 🌍 Internationalization (i18n)

### Languages Supported
- **Spanish (es)** - Default language
- **English (en)** - Alternative language

### Features
- Instant language switching from header dropdown
- Language preference saved to user profile
- Persistent localStorage backup
- 100+ translation keys
- SSR-safe implementation

### Using Translations

```tsx
import { useLanguage } from '@/lib/language-context';

export default function MyComponent() {
  const { t, language, setLanguage } = useLanguage();
  
  return (
    <div>
      <h1>{t('navigation.dashboard')}</h1>
      <button onClick={() => setLanguage('en')}>English</button>
    </div>
  );
}
```

### Translation Files
- `messages/es.json` - Spanish translations (200+ keys)
- `messages/en.json` - English translations (200+ keys)

### Translation Keys by Category
- `navigation.*` - Navigation menu items
- `auth.*` - Authentication pages
- `dashboard.*` - Dashboard content
- `patients.*` - Patient management
- `doctors.*` - Doctor management
- `appointments.*` - Appointment scheduling
- `prescriptions.*` - Prescription forms
- `search.*` - Search functionality
- `common.*` - Common actions
- `profile.*` - Profile settings
- `errors.*` - Error messages
- `messages.*` - Success/info messages

---

## Getting Started

### 1. Install Dependencies
```bash
npm install
```

### 2. Environment Setup
Create `.env.local` in the client directory:
```
NEXT_PUBLIC_API_URL=http://localhost:5000
```

### 3. Start Development Server
```bash
npm run dev
```

Visit `http://localhost:3000` in your browser.

### 4. Build for Production
```bash
npm run build
npm run start
```

---

## 📖 Pages & Routes

### Public Pages
- `/` - Landing page with features showcase
- `/login` - User login
- `/register` - User registration
- `/forgot-password` - Password recovery

### Protected Pages (Dashboard)
- `/dashboard` - Main dashboard with statistics
- `/dashboard/patients` - Patient management (list, add, search, delete)
- `/dashboard/doctors` - Doctor management (list, search, delete)
- `/dashboard/appointments` - Appointment calendar with status filtering
- `/dashboard/prescriptions` - Prescription form management
- `/dashboard/search` - Advanced search engine
- `/dashboard/profile` - User profile and settings

---

## 🎨 Components

### Layout Components
- **Header** - Navigation with language switcher and user dropdown
- **Sidebar** - Main navigation menu with icon support
- **MainLayout** - Page layout wrapper

### Feature Components
- **PatientList** - Display and manage patients
- **PatientForm** - Add/edit patient records
- **DoctorList** - Display and manage doctors
- **AppointmentCalendar** - View and manage appointments
- **PrescriptionForm** - Create and manage prescriptions
- **SearchComponent** - Advanced search with filters
- **LanguageSwitcher** - Change application language

### UI Components (shadcn/ui)
- 21+ pre-built components: Button, Card, Dialog, Form, Input, Select, Table, Tabs, etc.

---

## API Integration

### Base URL
```
http://localhost:5000/api
```

### Common Endpoints
```
// Patients
GET /api/patients
POST /api/patients
GET /api/patients/:id
PUT /api/patients/:id
DELETE /api/patients/:id

// Doctors
GET /api/doctors
POST /api/doctors
GET /api/doctors/:id
PUT /api/doctors/:id
DELETE /api/doctors/:id

// Appointments
GET /api/appointments
POST /api/appointments
GET /api/appointments/:id
PUT /api/appointments/:id
DELETE /api/appointments/:id

// Authentication
POST /api/auth/register
POST /api/auth/login
POST /api/auth/forgot-password
POST /api/auth/reset-password
POST /api/auth/verify
```

---

## 🚀 Features Implemented

### Phase 1: Core Features ✅
- ✅ Professional landing page
- ✅ User authentication (login, register, password reset)
- ✅ Patient management (CRUD operations)
- ✅ Doctor management
- ✅ Appointment scheduling and calendar
- ✅ Prescription forms
- ✅ Advanced search (name, email, phone)
- ✅ Dashboard with statistics
- ✅ Responsive design (mobile, tablet, desktop)
- ✅ Professional UI with shadcn/ui
- ✅ Internationalization (Spanish/English)
- ✅ User profile and settings
- ✅ Language preference persistence

### Phase 2: Enhanced Features ⏳
- [ ] Patient consultation history
- [ ] Exam/PDF attachments
- [ ] Medical history details
- [ ] Test results management
- [ ] Vital signs tracking

### Phase 3: Medical Visualization ⏳
- [ ] Interactive 2D/3D Odontogram
- [ ] Custom record templates
- [ ] Diagnosis templates

### Phase 4: Advanced Features ⏳
- [ ] PDF generation and printing
- [ ] Digital signature
- [ ] Doctor logo upload
- [ ] Notification system
- [ ] WhatsApp integration
- [ ] SMS integration
- [ ] Email notifications

### Phase 5: Payments ⏳
- [ ] Stripe integration
- [ ] PayPal integration
- [ ] Subscription management
- [ ] Invoice generation

---

## Project Structure

```
client/
├── app/
│   ├── layout.tsx
│   ├── page.tsx (Landing page)
│   ├── login/
│   ├── register/
│   ├── forgot-password/
│   ├── (dashboard)/
│   │   ├── layout.tsx
│   │   ├── dashboard/
│   │   ├── patients/
│   │   ├── doctors/
│   │   ├── appointments/
│   │   ├── prescriptions/
│   │   ├── search/
│   │   └── profile/
│   ├── components/
│   │   ├── Layout/
│   │   ├── Patient/
│   │   ├── Doctor/
│   │   ├── Appointment/
│   │   ├── Prescription/
│   │   └── Search/
│   ├── lib/
│   │   ├── auth-context.tsx
│   │   ├── auth-service.ts
│   │   ├── auth-schemas.ts
│   │   ├── language-context.tsx
│   │   ├── profile-service.ts
│   │   └── utils.ts
│   ├── messages/
│   │   ├── es.json
│   │   └── en.json
│   └── types/
├── components/
│   └── ui/ (21+ shadcn/ui components)
├── public/
├── package.json
└── tsconfig.json
```

---

## Key Features

### Search Engine
- Search by patient name (first or last)
- Search by email address
- Search by phone number
- Ready for: date range filtering, diagnosis filtering

### Appointment Management
- View appointments by date
- Status filtering (scheduled, completed, cancelled)
- Color-coded status badges
- Appointment details with patient and doctor info

### Prescription System
- Create prescriptions with dosage and duration
- Medication support
- ICD-10 diagnosis codes
- CDT dental diagnosis codes
- Notes for special instructions
- Ready for: PDF generation, printing, digital signature, doctor logo

### Advanced Search
- Multi-field search
- Real-time filtering
- Patient result highlighting
- Quick access to patient details

---

## Development Guidelines

### Before Starting Development, ALWAYS:

1. **Read entire AI instructions** - Understand all guidelines
2. **Read README entirely** - Don't generate code without understanding the scope
3. **Develop for all devices** - Mobile, tablet, and desktop responsive
4. **Know the file structure** - Understand project organization
5. **Use existing code** - Extend and reuse existing components
6. **Maintain reusable components** - Avoid code duplication
7. **UI must be professional** - Support 1M+ users
8. **Follow requirements** - Strictly adhere to specifications

---

## Environment Variables

Create `.env.local`:
```
NEXT_PUBLIC_API_URL=http://localhost:5000
```

---

## Testing the Application

### Register a New User
1. Go to `/register`
2. Fill in your details
3. Select user type
4. Click "Sign Up"

### Login
1. Go to `/login`
2. Enter email and password from registration
3. Click "Sign In"
4. You'll be redirected to the dashboard

### View Dashboard
1. Access `/dashboard` after login
2. View statistics and recent data
3. Navigate using the sidebar menu

### Manage Patients
1. Go to `/dashboard/patients`
2. View patient list
3. Click "Add Patient" to create new patient
4. Use search to filter patients

### Schedule Appointments
1. Go to `/dashboard/appointments`
2. View appointment calendar
3. Filter by status
4. Create new appointments

### Change Language
1. Look for language dropdown in top-right corner
2. Select Spanish or English
3. Entire interface switches instantly
4. Preference is saved to your profile

---

## Common Tasks

### Add New Translation Keys
1. Add to `messages/es.json`:
```json
{
  "myFeature": {
    "title": "Mi Característica"
  }
}
```

2. Add to `messages/en.json`:
```json
{
  "myFeature": {
    "title": "My Feature"
  }
}
```

3. Use in component:
```tsx
const { t } = useLanguage();
<h1>{t('myFeature.title')}</h1>
```

### Add New Patient Fields
1. Update Patient model in backend
2. Add to patient form component
3. Update TypeScript types
4. Add translation keys if UI needs labels

### Create New Dashboard Page
1. Create new folder in `app/(dashboard)/`
2. Add `page.tsx` file
3. Add navigation link in Sidebar
4. Add translation key for navigation
5. Implement page component

---

## Performance Tips

- Use `next/image` for images
- Lazy load components with dynamic imports
- Implement pagination for large lists
- Use React Context efficiently
- Cache API responses when appropriate
- Optimize bundle size with next/dynamic

---

## Troubleshooting

### "Cannot connect to API"
- Check if backend server is running on port 5000
- Verify NEXT_PUBLIC_API_URL in `.env.local`
- Check network tab in browser DevTools

### "Language not changing"
- Clear browser localStorage
- Check `language-context.tsx` is wrapped around app
- Verify translation keys exist in JSON files

### "Authentication not working"
- Check backend JWT_SECRET is set
- Verify token is stored in localStorage
- Check browser console for error messages
- Ensure MongoDB is running

### "Components not rendering"
- Clear `.next` build cache: `rm -rf .next`
- Reinstall node modules: `npm install`
- Restart development server

---

## Deployment

### Vercel (Recommended)
1. Push to GitHub
2. Connect repository to Vercel
3. Set environment variables in Vercel dashboard
4. Deploy

### Other Platforms
- Netlify
- AWS Amplify
- Azure Static Web Apps
- Self-hosted with Docker

---

## Version History

- **v1.0** (February 2026) - MVP release with core features, authentication, and i18n

---

**Last Updated**: February 2026
**Status**: Production Ready

## UI Components - shadcn/ui

This project uses **shadcn/ui** for building high-quality, accessible UI components.

### Installation & Setup
✔ Successfully initialized shadcn/ui with the following configuration:
- **Base Color**: Slate
- **Framework**: Next.js with Tailwind CSS v4
- **Utilities**: Created `lib/utils.ts` with class merging utilities

### Installed Components
✔ **21 Components** installed: button, form, input, textarea, select, checkbox, radio-group, label, table, card, badge, tabs, dropdown-menu, sheet, dialog, alert, tooltip, calendar, popover, skeleton, pagination, progress

## Project Structure

### Frontend (`/client`)
- **Layout Components**: Header, Sidebar, MainLayout for dashboard
- **Patient Management**: PatientList, PatientForm
- **Doctor Management**: DoctorList  
- **Appointments**: AppointmentCalendar with status filtering
- **Dashboard**: Dashboard page with statistics and metrics
- **Pages**: 
  - `/` - Landing page with features overview
  - `/dashboard` - Main dashboard with stats
  - `/patients` - Patient management
  - `/doctors` - Doctor management
  - `/appointments` - Appointment calendar

### Backend (`/server`)
- **Models**: Patient, Doctor, Appointment with MongoDB schemas
- **Services**: PatientService, DoctorService, AppointmentService
- **Controllers**: RESTful API endpoints for all resources
- **API Routes**:
  - `GET/POST /api/patients` - Patient management
  - `GET/POST /api/doctors` - Doctor management
  - `GET/POST /api/appointments` - Appointment management

## Development Setup

### Prerequisites
- Node.js (v16+)
- MongoDB (local or cloud)

### Backend Setup
```bash
cd server
npm install
cp .env.example .env
# Update .env with your MongoDB URI
npm run dev
```

The server will run on `http://localhost:5000`

API Health Check: `http://localhost:5000/api/health`

### Frontend Setup
```bash
cd client
npm install
npm run dev
```

The client will run on `http://localhost:3000`

## Adding More Components

To add additional shadcn/ui components:
```bash
npx shadcn@latest add [component-name]
```

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
