// Patient Records Module

let currentEditingPatient = null;

const therapyTypes = [
    'Speech Therapy',
    'Occupational Therapy', 
    'Play and Social Skills Therapy',
    'Special Education',
    'Deep Tissue Massage',
    'Physiotherapy',
    'Comprehensive Neurohabilitative Assessment',
    'Paediatric Neurologist Consultation'
];

function loadPatientsData() {
    // First, add the patients section to the HTML if it doesn't exist
    addPatientsSection();
    
    const patientsTableBody = document.querySelector('#patients-table tbody');
    const patients = window.app.getData('patients');
    
    patientsTableBody.innerHTML = patients.map(patient => `
        <tr>
            <td>${patient.name}</td>
            <td>${patient.age}</td>
            <td>${patient.guardian}</td>
            <td>${patient.contact}</td>
            <td>${patient.problemType}</td>
            <td>${patient.therapyType}</td>
            <td>${patient.lastVisit ? window.app.formatDate(patient.lastVisit) : 'No visits'}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="recordVisit(${patient.id})">
                    <i class="fas fa-plus"></i> Visit
                </button>
                <button class="btn btn-sm btn-warning" onclick="editPatient(${patient.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deletePatient(${patient.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');

    // Setup therapy type filter
    const therapyFilter = document.getElementById('patient-therapy-filter');
    if (therapyFilter) {
        therapyFilter.addEventListener('change', filterPatientsByTherapy);
    }

    // Load patient summary
    loadPatientSummary();
}

function addPatientsSection() {
    const patientsSection = document.getElementById('patients');
    if (patientsSection && !patientsSection.querySelector('#patients-table')) {
        patientsSection.innerHTML = `
            <div class="section-header">
                <h2>Patient Records</h2>
                <button class="btn btn-primary" onclick="showPatientModal()">
                    <i class="fas fa-user-plus"></i> Add Patient
                </button>
            </div>
            
            <div class="filters">
                <select id="patient-therapy-filter">
                    <option value="">All Therapy Types</option>
                    ${therapyTypes.map(type => `<option value="${type}">${type}</option>`).join('')}
                </select>
                <button class="btn btn-secondary" onclick="exportPatients()">
                    <i class="fas fa-download"></i> Export Patients
                </button>
            </div>

            <div class="table-container">
                <table id="patients-table">
                    <thead>
                        <tr>
                            <th>Patient Name</th>
                            <th>Age</th>
                            <th>Parent/Guardian</th>
                            <th>Contact</th>
                            <th>Problem Type</th>
                            <th>Therapy Type</th>
                            <th>Last Visit</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Patients data will be populated here -->
                    </tbody>
                </table>
            </div>

            <div id="patient-summary" class="patient-summary">
                <h3>Patient Summary</h3>
                <div class="summary-grid">
                    <div class="summary-card">
                        <h4>Total Patients</h4>
                        <div class="summary-amount" id="total-patients-count">0</div>
                    </div>
                    <div class="summary-card">
                        <h4>Active This Month</h4>
                        <div class="summary-amount" id="active-patients-count">0</div>
                    </div>
                    <div class="summary-card">
                        <h4>Most Common Therapy</h4>
                        <div class="summary-amount" id="common-therapy">-</div>
                    </div>
                </div>
                <div class="therapy-breakdown" id="therapy-breakdown">
                    <!-- Therapy type breakdown will be populated here -->
                </div>
            </div>
        `;
    }
}

function filterPatientsByTherapy() {
    const filter = document.getElementById('patient-therapy-filter').value;
    const patients = window.app.getData('patients');
    const filteredPatients = filter ? patients.filter(patient => patient.therapyType === filter) : patients;
    
    const patientsTableBody = document.querySelector('#patients-table tbody');
    patientsTableBody.innerHTML = filteredPatients.map(patient => `
        <tr>
            <td>${patient.name}</td>
            <td>${patient.age}</td>
            <td>${patient.guardian}</td>
            <td>${patient.contact}</td>
            <td>${patient.problemType}</td>
            <td>${patient.therapyType}</td>
            <td>${patient.lastVisit ? window.app.formatDate(patient.lastVisit) : 'No visits'}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="recordVisit(${patient.id})">
                    <i class="fas fa-plus"></i> Visit
                </button>
                <button class="btn btn-sm btn-warning" onclick="editPatient(${patient.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deletePatient(${patient.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');
}

function showPatientModal(patientId = null) {
    const patient = patientId ? window.app.getData('patients').find(p => p.id === patientId) : null;
    const isEdit = !!patient;
    
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>${isEdit ? 'Edit Patient' : 'Add New Patient'}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="patient-form">
                    <div class="form-group">
                        <label for="patient-name">Patient Name *</label>
                        <input type="text" id="patient-name" name="name" required 
                               value="${patient ? patient.name : ''}" placeholder="Enter patient's full name">
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-age">Age *</label>
                        <input type="number" id="patient-age" name="age" required min="0" max="150"
                               value="${patient ? patient.age : ''}" placeholder="Enter age">
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-guardian">Parent/Guardian Name *</label>
                        <input type="text" id="patient-guardian" name="guardian" required 
                               value="${patient ? patient.guardian : ''}" placeholder="Enter parent/guardian name">
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-contact">Contact Information *</label>
                        <input type="text" id="patient-contact" name="contact" required 
                               value="${patient ? patient.contact : ''}" placeholder="Phone number or email">
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-problem">Type of Problem *</label>
                        <textarea id="patient-problem" name="problemType" required rows="3"
                                  placeholder="Describe the patient's condition or problem">${patient ? patient.problemType || '' : ''}</textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-therapy">Type of Therapy *</label>
                        <select id="patient-therapy" name="therapyType" required>
                            <option value="">Select Therapy Type</option>
                            ${therapyTypes.map(type => `
                                <option value="${type}" ${patient && patient.therapyType === type ? 'selected' : ''}>${type}</option>
                            `).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-address">Address</label>
                        <textarea id="patient-address" name="address" rows="2" 
                                  placeholder="Patient's address">${patient ? patient.address || '' : ''}</textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-emergency">Emergency Contact</label>
                        <input type="text" id="patient-emergency" name="emergencyContact" 
                               value="${patient ? patient.emergencyContact || '' : ''}" 
                               placeholder="Emergency contact number">
                    </div>
                    
                    <div class="form-group">
                        <label for="patient-notes">Medical Notes</label>
                        <textarea id="patient-notes" name="notes" rows="3" 
                                  placeholder="Additional medical notes or observations">${patient ? patient.notes || '' : ''}</textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="savePatient(${patientId})">
                    <i class="fas fa-save"></i> ${isEdit ? 'Update' : 'Add'} Patient
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    currentEditingPatient = patientId;
}

function savePatient(patientId) {
    const form = document.getElementById('patient-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['name', 'age', 'guardian', 'contact', 'problemType', 'therapyType'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field.replace(/([A-Z])/g, ' $1').toLowerCase()} field`, 'error');
            return;
        }
    }
    
    const patientData = {
        id: patientId || window.app.generateId('patients'),
        name: formData.get('name'),
        age: parseInt(formData.get('age')),
        guardian: formData.get('guardian'),
        contact: formData.get('contact'),
        problemType: formData.get('problemType'),
        therapyType: formData.get('therapyType'),
        address: formData.get('address') || '',
        emergencyContact: formData.get('emergencyContact') || '',
        notes: formData.get('notes') || '',
        visits: patientId ? window.app.getData('patients').find(p => p.id === patientId)?.visits || [] : [],
        lastVisit: patientId ? window.app.getData('patients').find(p => p.id === patientId)?.lastVisit : null,
        createdAt: patientId ? undefined : new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    
    let patients = window.app.getData('patients');
    
    if (patientId) {
        // Update existing patient
        const index = patients.findIndex(p => p.id === patientId);
        if (index !== -1) {
            patients[index] = { ...patients[index], ...patientData };
        }
    } else {
        // Add new patient
        patients.push(patientData);
    }
    
    window.app.saveData('patients', patients);
    window.app.closeModal();
    loadPatientsData();
    
    window.app.showNotification(
        `Patient ${patientId ? 'updated' : 'added'} successfully!`,
        'success'
    );
}

function editPatient(patientId) {
    showPatientModal(patientId);
}

function deletePatient(patientId) {
    const patient = window.app.getData('patients').find(p => p.id === patientId);
    if (confirm(`Are you sure you want to delete ${patient?.name}'s record? This action cannot be undone.`)) {
        let patients = window.app.getData('patients');
        patients = patients.filter(p => p.id !== patientId);
        window.app.saveData('patients', patients);
        loadPatientsData();
        window.app.showNotification('Patient record deleted successfully!', 'success');
    }
}

function recordVisit(patientId) {
    const patient = window.app.getData('patients').find(p => p.id === patientId);
    if (!patient) return;
    
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>Record Visit - ${patient.name}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="visit-form">
                    <div class="form-group">
                        <label for="visit-date">Visit Date *</label>
                        <input type="date" id="visit-date" name="date" required 
                               value="${new Date().toISOString().split('T')[0]}">
                    </div>
                    
                    <div class="form-group">
                        <label for="visit-time-in">Time In *</label>
                        <input type="time" id="visit-time-in" name="timeIn" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="visit-time-out">Time Out</label>
                        <input type="time" id="visit-time-out" name="timeOut">
                    </div>
                    
                    <div class="form-group">
                        <label for="visit-therapist">Therapist</label>
                        <select id="visit-therapist" name="therapist">
                            <option value="">Select Therapist</option>
                            ${getTherapistOptions()}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="visit-therapy-type">Therapy Type</label>
                        <select id="visit-therapy-type" name="therapyType">
                            <option value="${patient.therapyType}" selected>${patient.therapyType}</option>
                            ${therapyTypes.filter(type => type !== patient.therapyType).map(type => 
                                `<option value="${type}">${type}</option>`
                            ).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="visit-notes">Session Notes</label>
                        <textarea id="visit-notes" name="notes" rows="4" 
                                  placeholder="Notes about the therapy session, progress, observations, etc."></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="visit-fee">Session Fee</label>
                        <input type="number" id="visit-fee" name="fee" step="0.01" min="0" 
                               placeholder="Enter session fee (default: Ksh 7,500)">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveVisit(${patientId})">
                    <i class="fas fa-save"></i> Record Visit
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
}

function getTherapistOptions() {
    const staff = window.app.getData('staff');
    const therapists = staff.filter(member => member.department === 'therapist');
    return therapists.map(therapist => 
        `<option value="${therapist.name}">${therapist.name} - ${therapist.role}</option>`
    ).join('');
}

function saveVisit(patientId) {
    const form = document.getElementById('visit-form');
    const formData = new FormData(form);
    
    // Validate required fields
    if (!formData.get('date') || !formData.get('timeIn')) {
        window.app.showNotification('Please fill in the required fields', 'error');
        return;
    }
    
    const visitData = {
        id: Date.now(), // Simple ID generation for visits
        date: formData.get('date'),
        timeIn: formData.get('timeIn'),
        timeOut: formData.get('timeOut') || null,
        therapist: formData.get('therapist') || '',
        therapyType: formData.get('therapyType'),
        notes: formData.get('notes') || '',
        fee: parseFloat(formData.get('fee') || 7500),
        createdAt: new Date().toISOString()
    };
    
    let patients = window.app.getData('patients');
    const patientIndex = patients.findIndex(p => p.id === patientId);
    
    if (patientIndex !== -1) {
        if (!patients[patientIndex].visits) {
            patients[patientIndex].visits = [];
        }
        patients[patientIndex].visits.push(visitData);
        patients[patientIndex].lastVisit = visitData.date;
        patients[patientIndex].updatedAt = new Date().toISOString();
        
        window.app.saveData('patients', patients);
        window.app.closeModal();
        loadPatientsData();
        
        window.app.showNotification('Visit recorded successfully!', 'success');
    }
}

function loadPatientSummary() {
    const patients = window.app.getData('patients');
    const currentDate = new Date();
    const currentMonth = currentDate.getMonth();
    const currentYear = currentDate.getFullYear();
    
    // Total patients
    document.getElementById('total-patients-count').textContent = patients.length;
    
    // Active patients this month (patients with visits this month)
    const activePatients = patients.filter(patient => {
        if (!patient.visits || patient.visits.length === 0) return false;
        return patient.visits.some(visit => {
            const visitDate = new Date(visit.date);
            return visitDate.getMonth() === currentMonth && visitDate.getFullYear() === currentYear;
        });
    });
    
    document.getElementById('active-patients-count').textContent = activePatients.length;
    
    // Most common therapy type
    const therapyCount = {};
    patients.forEach(patient => {
        therapyCount[patient.therapyType] = (therapyCount[patient.therapyType] || 0) + 1;
    });
    
    const mostCommon = Object.entries(therapyCount).reduce((a, b) => 
        therapyCount[a[0]] > therapyCount[b[0]] ? a : b, ['None', 0]
    );
    
    document.getElementById('common-therapy').textContent = mostCommon[0];
    
    // Therapy breakdown
    const breakdownContainer = document.getElementById('therapy-breakdown');
    breakdownContainer.innerHTML = `
        <h4>Therapy Type Distribution</h4>
        <div class="therapy-stats">
            ${Object.entries(therapyCount).map(([therapy, count]) => `
                <div class="therapy-stat">
                    <span class="therapy-name">${therapy}</span>
                    <span class="therapy-count">${count} patients</span>
                    <div class="therapy-bar">
                        <div class="therapy-fill" style="width: ${(count / patients.length) * 100}%"></div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
}

function exportPatients() {
    const patients = window.app.getData('patients');
    
    if (patients.length === 0) {
        window.app.showNotification('No patients to export', 'error');
        return;
    }
    
    const exportData = patients.map(patient => ({
        'Patient Name': patient.name,
        'Age': patient.age,
        'Parent/Guardian': patient.guardian,
        'Contact': patient.contact,
        'Problem Type': patient.problemType,
        'Therapy Type': patient.therapyType,
        'Address': patient.address || '',
        'Emergency Contact': patient.emergencyContact || '',
        'Total Visits': patient.visits ? patient.visits.length : 0,
        'Last Visit': patient.lastVisit || 'No visits',
        'Notes': patient.notes || ''
    }));
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(exportData, `patients-${currentDate}.csv`);
    window.app.showNotification('Patients exported successfully!', 'success');
}

// Add CSS for patient summary styles
const patientStyles = `
    <style>
        .patient-summary {
            background: var(--white);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            margin-top: 2rem;
        }
        
        .patient-summary h3 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
        }
        
        .therapy-breakdown {
            margin-top: 2rem;
        }
        
        .therapy-breakdown h4 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
        }
        
        .therapy-stats {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .therapy-stat {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .therapy-name {
            min-width: 200px;
            font-weight: 500;
        }
        
        .therapy-count {
            min-width: 100px;
            font-size: 0.9rem;
            color: #666;
        }
        
        .therapy-bar {
            flex: 1;
            height: 20px;
            background: var(--light-gray);
            border-radius: 10px;
            overflow: hidden;
        }
        
        .therapy-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--primary-teal), var(--light-teal));
            transition: width 0.3s ease;
        }
    </style>
`;

document.head.insertAdjacentHTML('beforeend', patientStyles);
