// Patient Import JavaScript Handler
let csvData = null;
let parsedData = null;
let columnMapping = {};
let validatedData = null;
let currentStep = 1;

// Field mapping configuration
const fieldMappings = {
    // Patient Basic Info
    'CompanyName': { db: 'company_name', required: false },
    'RegistrationDate': { db: 'registration_date', required: true, type: 'date' },
    'PatientNumber_reg': { db: 'patient_number', required: true },
    'PatientNumber_clin': { db: 'patient_number', required: false },
    'Gender': { db: 'gender', required: true },
    'Age': { db: 'age', required: false, type: 'age' },
    'PatientName': { db: 'full_name', required: true },
    'PhoneNumber': { db: 'phone_number', required: false },
    'MaritalStatus': { db: 'marital_status', required: false },
    'MembershipNumber': { db: 'membership_number', required: false },
    
    // Doctor & Clinical Info
    'DoctorName': { db: 'doctor_name', required: false },
    'DoctorID': { db: 'doctor_id', required: false },
    'Room': { db: 'room', required: false },
    
    // Patient Type & Status
    'PatientType': { db: 'patient_type', required: false },
    'PatientStatus_reg': { db: 'patient_status', required: false },
    'PatientStatus_clin': { db: 'patient_status', required: false },
    
    // Payment & Insurance
    'PayableBy_reg': { db: 'payable_by', required: false },
    'PayableBy_clin': { db: 'payable_by', required: false },
    'MedicalSchemeID': { db: 'insurance_provider_id', required: false },
    
    // Clinical Information
    'ConsultDescription_reg': { db: 'consultation_description', required: false },
    'ConsultDescription_clin': { db: 'consultation_description', required: false },
    'Diagnosis_reg': { db: 'diagnosis', required: false },
    'Diagnosis_clin': { db: 'diagnosis', required: false },
    'Diagnosis.1': { db: 'diagnosis', required: false },
    'ClinicalHpi': { db: 'clinical_hpi', required: false },
    'ClinicalHpi.1': { db: 'clinical_hpi', required: false },
    'Symptoms': { db: 'symptoms', required: false },
    'Symptoms.1': { db: 'symptoms', required: false },
    'Findings': { db: 'findings', required: false },
    'Management': { db: 'management', required: false },
    'Management.1': { db: 'management', required: false },
    'InvestigationRemarks': { db: 'investigation_remarks', required: false },
    'DiagnosisCategory': { db: 'diagnosis_category', required: false },
    'ClinicalNotes': { db: 'clinical_notes', required: false },
    'NextApptPurpose': { db: 'next_appointment_purpose', required: false },
    
    // Service & Invoice Info
    'ServiceDate': { db: 'service_date', required: false, type: 'date' },
    'InvoiceNumber': { db: 'invoice_number', required: false },
    'QueueID': { db: 'queue_id', required: false }
};

$(document).ready(function() {
    console.log('Patient import script loaded');
    initializeUpload();
    initializeStepNavigation();
});

function initializeUpload() {
    const uploadArea = $('#uploadArea');
    const fileInput = $('#csvFile');

    console.log('Initializing upload handlers');

    // Click to upload
    uploadArea.on('click', function(e) {
        console.log('Upload area clicked');
        if (!$(e.target).is('button')) {
            fileInput.click();
        }
    });

    // File input change
    fileInput.on('change', function(e) {
        console.log('File selected:', e.target.files[0]);
        if (e.target.files && e.target.files[0]) {
            handleFileSelect(e.target.files[0]);
        }
    });

    // Drag and drop
    uploadArea.on('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass('dragover');
    });

    uploadArea.on('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass('dragover');
    });

    uploadArea.on('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass('dragover');
        
        const files = e.originalEvent.dataTransfer.files;
        console.log('Files dropped:', files.length);
        if (files.length > 0) {
            handleFileSelect(files[0]);
        }
    });

    // Remove file
    $('#removeFile').on('click', function(e) {
        e.stopPropagation();
        resetUpload();
    });
}

function handleFileSelect(file) {
    console.log('Handling file:', file.name, 'Size:', file.size, 'Type:', file.type);
    
    if (!file) {
        console.error('No file provided');
        return;
    }

    if (!file.name.endsWith('.csv')) {
        Swal.fire({
            icon: 'error',
            title: 'Invalid File Type',
            text: 'Please upload a CSV file'
        });
        return;
    }

    $('#fileName').text(file.name);
    $('#fileSize').text(formatFileSize(file.size));
    $('#fileInfo').show();
    $('#btnStep1Next').prop('disabled', false);

    console.log('Starting CSV parse...');
    
    // Parse CSV
    Papa.parse(file, {
        header: true,
        skipEmptyLines: true,
        dynamicTyping: false, // Keep all as strings initially
        complete: function(results) {
            console.log('CSV parsed successfully:', results);
            console.log('Rows:', results.data.length);
            console.log('Columns:', results.meta.fields);
            
            csvData = results;
            parsedData = results.data;
            
            Swal.fire({
                icon: 'success',
                title: 'File Loaded!',
                text: `Successfully loaded ${results.data.length} records`,
                timer: 2000,
                showConfirmButton: false
            });
        },
        error: function(error) {
            console.error('CSV parse error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Parse Error',
                text: 'Failed to parse CSV file: ' + error.message
            });
            resetUpload();
        }
    });
}

function resetUpload() {
    $('#csvFile').val('');
    $('#fileInfo').hide();
    $('#btnStep1Next').prop('disabled', true);
    csvData = null;
    parsedData = null;
}

function formatFileSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}

function initializeStepNavigation() {
    $('#btnStep1Next').on('click', function() {
        console.log('Step 1 Next clicked');
        if (!parsedData) {
            Swal.fire({
                icon: 'error',
                title: 'No File',
                text: 'Please upload a CSV file first'
            });
            return;
        }
        moveToStep(2);
        generateColumnMappings();
    });

    $('#btnStep2Back').on('click', () => moveToStep(1));
    $('#btnStep2Next').on('click', function() {
        console.log('Step 2 Next clicked');
        if (validateMappings()) {
            moveToStep(3);
            previewAndValidate();
        }
    });

    $('#btnStep3Back').on('click', () => moveToStep(2));
    $('#btnStep3Next').on('click', () => {
        if (validatedData && validatedData.validCount > 0) {
            moveToStep(4);
            prepareImport();
        } else {
            Swal.fire({
                icon: 'error',
                title: 'No Valid Records',
                text: 'No valid records to import'
            });
        }
    });

    $('#btnStep4Back').on('click', () => moveToStep(3));
    $('#btnStartImport').on('click', startImport);
}

function moveToStep(step) {
    console.log('Moving to step:', step);
    
    // Update step indicators
    $('.step').removeClass('active completed');
    for (let i = 1; i < step; i++) {
        $(`.step[data-step="${i}"]`).addClass('completed');
    }
    $(`.step[data-step="${step}"]`).addClass('active');

    // Show/hide step content
    $('.import-section').removeClass('active');
    $(`#step${step}`).addClass('active');
    
    currentStep = step;

    // Scroll to top
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function generateColumnMappings() {
    console.log('Generating column mappings');
    
    if (!csvData || !csvData.meta || !csvData.meta.fields) {
        console.error('No CSV data or fields');
        return;
    }

    const columns = csvData.meta.fields;
    console.log('CSV Columns:', columns);
    
    const mappingsHtml = columns.map(col => {
        const mapping = fieldMappings[col];
        const dbField = mapping ? mapping.db : '';
        const isRequired = mapping ? mapping.required : false;
        
        return `
            <div class="mapping-row">
                <div style="flex: 0 0 35%;">
                    <strong>${col}</strong>
                    ${isRequired ? '<span class="badge bg-danger ms-2">Required</span>' : ''}
                </div>
                <div style="flex: 0 0 10%; text-align: center;">
                    <i class="ri-arrow-right-line text-muted"></i>
                </div>
                <div style="flex: 1;">
                    <select class="form-select form-select-sm column-map" 
                            data-csv-column="${col}">
                        <option value="">-- Skip this column --</option>
                        <optgroup label="Patient Information">
                            <option value="full_name" ${dbField === 'full_name' ? 'selected' : ''}>Patient Name</option>
                            <option value="patient_number" ${dbField === 'patient_number' ? 'selected' : ''}>Patient Number</option>
                            <option value="gender" ${dbField === 'gender' ? 'selected' : ''}>Gender</option>
                            <option value="age" ${dbField === 'age' ? 'selected' : ''}>Age</option>
                            <option value="phone_number" ${dbField === 'phone_number' ? 'selected' : ''}>Phone Number</option>
                            <option value="marital_status" ${dbField === 'marital_status' ? 'selected' : ''}>Marital Status</option>
                            <option value="membership_number" ${dbField === 'membership_number' ? 'selected' : ''}>Membership Number</option>
                        </optgroup>
                        <optgroup label="Registration">
                            <option value="registration_date" ${dbField === 'registration_date' ? 'selected' : ''}>Registration Date</option>
                            <option value="patient_type" ${dbField === 'patient_type' ? 'selected' : ''}>Patient Type</option>
                            <option value="patient_status" ${dbField === 'patient_status' ? 'selected' : ''}>Patient Status</option>
                            <option value="company_name" ${dbField === 'company_name' ? 'selected' : ''}>Company Name</option>
                        </optgroup>
                        <optgroup label="Clinical">
                            <option value="doctor_name" ${dbField === 'doctor_name' ? 'selected' : ''}>Doctor Name</option>
                            <option value="consultation_description" ${dbField === 'consultation_description' ? 'selected' : ''}>Consultation Description</option>
                            <option value="diagnosis" ${dbField === 'diagnosis' ? 'selected' : ''}>Diagnosis</option>
                            <option value="symptoms" ${dbField === 'symptoms' ? 'selected' : ''}>Symptoms</option>
                            <option value="findings" ${dbField === 'findings' ? 'selected' : ''}>Findings</option>
                            <option value="management" ${dbField === 'management' ? 'selected' : ''}>Management</option>
                            <option value="clinical_hpi" ${dbField === 'clinical_hpi' ? 'selected' : ''}>Clinical HPI</option>
                            <option value="clinical_notes" ${dbField === 'clinical_notes' ? 'selected' : ''}>Clinical Notes</option>
                        </optgroup>
                        <optgroup label="Payment & Insurance">
                            <option value="payable_by" ${dbField === 'payable_by' ? 'selected' : ''}>Payable By</option>
                            <option value="insurance_provider_id" ${dbField === 'insurance_provider_id' ? 'selected' : ''}>Insurance Provider</option>
                        </optgroup>
                    </select>
                </div>
            </div>
        `;
    }).join('');

    $('#columnMappings').html(mappingsHtml);
}

function validateMappings() {
    columnMapping = {};
    let hasPatientNumber = false;
    let hasPatientName = false;

    $('.column-map').each(function() {
        const csvCol = $(this).data('csv-column');
        const dbField = $(this).val();
        if (dbField) {
            columnMapping[csvCol] = dbField;
            if (dbField === 'patient_number') hasPatientNumber = true;
            if (dbField === 'full_name') hasPatientName = true;
        }
    });

    console.log('Column mapping:', columnMapping);

    if (!hasPatientNumber) {
        Swal.fire({
            icon: 'error',
            title: 'Missing Required Field',
            text: 'Patient Number field is required. Please map it.'
        });
        return false;
    }

    if (!hasPatientName) {
        Swal.fire({
            icon: 'error',
            title: 'Missing Required Field',
            text: 'Patient Name field is required. Please map it.'
        });
        return false;
    }

    return true;
}

function previewAndValidate() {
    console.log('Starting preview and validation');
    
    const errors = [];
    const validRecords = [];
    const groupedByPatient = {};

    // Group records by patient number
    parsedData.forEach((row, index) => {
        const mappedRow = {};
        let hasData = false;
        
        Object.keys(columnMapping).forEach(csvCol => {
            const dbField = columnMapping[csvCol];
            let value = row[csvCol];
            
            // Convert null/undefined to empty string
            if (value === null || value === undefined || value === 'null') {
                value = '';
            } else {
                value = String(value).trim();
            }
            
            if (value) {
                mappedRow[dbField] = value;
                hasData = true;
            }
        });

        if (hasData) {
            // Validate required fields
            if (!mappedRow.patient_number) {
                errors.push(`Row ${index + 2}: Missing patient number`);
                return;
            }
            if (!mappedRow.full_name) {
                errors.push(`Row ${index + 2}: Missing patient name`);
                return;
            }

            // Group by patient number
            if (!groupedByPatient[mappedRow.patient_number]) {
                groupedByPatient[mappedRow.patient_number] = {
                    patientInfo: {},
                    visits: []
                };
            }

            // Separate patient info from visit info
            const patientFields = ['full_name', 'gender', 'age', 'phone_number', 'patient_number', 
                                 'registration_date', 'marital_status', 'membership_number', 
                                 'patient_type', 'company_name'];
            
            patientFields.forEach(field => {
                if (mappedRow[field]) {
                    groupedByPatient[mappedRow.patient_number].patientInfo[field] = mappedRow[field];
                }
            });

            // Visit/clinical information
            const visitFields = ['service_date', 'doctor_name', 'consultation_description', 
                               'diagnosis', 'symptoms', 'findings', 'management', 'clinical_hpi',
                               'clinical_notes', 'payable_by', 'invoice_number'];
            
            const visitData = {};
            let hasVisitData = false;
            visitFields.forEach(field => {
                if (mappedRow[field]) {
                    visitData[field] = mappedRow[field];
                    hasVisitData = true;
                }
            });

            if (hasVisitData) {
                groupedByPatient[mappedRow.patient_number].visits.push(visitData);
            }

            validRecords.push(mappedRow);
        }
    });

    validatedData = {
        totalCount: parsedData.length,
        validCount: Object.keys(groupedByPatient).length,
        errorCount: errors.length,
        errors: errors,
        groupedData: groupedByPatient
    };

    console.log('Validation complete:', validatedData);

    // Update summary stats
    $('#totalRecords').text(validatedData.totalCount);
    $('#validRecords').text(validatedData.validCount);
    $('#errorRecords').text(validatedData.errorCount);

    // Show errors if any
    if (errors.length > 0) {
        $('#validationErrors').show();
        $('#errorList').html(errors.map(err => `<div class="small mb-1">${err}</div>`).join(''));
    } else {
        $('#validationErrors').hide();
    }

    // Generate preview
    generatePreview(validRecords.slice(0, 10));
}

function generatePreview(records) {
    if (records.length === 0) {
        $('#previewTable').html('<tr><td class="text-center p-4">No records to preview</td></tr>');
        return;
    }

    // Generate headers
    const fields = Object.keys(records[0]);
    const headerHtml = fields.map(field => 
        `<th class="text-nowrap">${field.replace(/_/g, ' ').toUpperCase()}</th>`
    ).join('');
    $('#previewHeaders').html(headerHtml);

    // Generate rows
    const rowsHtml = records.map(record => {
        const cells = fields.map(field => {
            const value = record[field] || '-';
            return `<td class="small">${value.length > 50 ? value.substring(0, 50) + '...' : value}</td>`;
        }).join('');
        return `<tr>${cells}</tr>`;
    }).join('');
    $('#previewBody').html(rowsHtml);
}

function prepareImport() {
    $('#importCount').text(validatedData.validCount);
}

function startImport() {
    if (!validatedData || !validatedData.groupedData) {
        Swal.fire({
            icon: 'error',
            title: 'No Data',
            text: 'No data to import'
        });
        return;
    }

    const skipDuplicates = $('#skipDuplicates').is(':checked');
    const updateExisting = $('#updateExisting').is(':checked');

    Swal.fire({
        title: 'Confirm Import',
        html: `You are about to import <strong>${validatedData.validCount}</strong> patient records.<br><br>
               ${skipDuplicates ? '✓ Skip duplicates<br>' : ''}
               ${updateExisting ? '✓ Update existing records<br>' : ''}
               <br>This action cannot be undone.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, Import Now'
    }).then((result) => {
        if (result.isConfirmed) {
            performImport(skipDuplicates, updateExisting);
        }
    });
}

function performImport(skipDuplicates, updateExisting) {
    $('#btnStartImport').prop('disabled', true);
    $('#btnStep4Back').prop('disabled', true);
    $('.import-progress').show();

    const patients = Object.values(validatedData.groupedData);
    let processed = 0;
    let imported = 0;
    let skipped = 0;
    let errors = 0;

    function importBatch(startIndex) {
        const batchSize = 10;
        const batch = patients.slice(startIndex, startIndex + batchSize);

        if (batch.length === 0) {
            // Import complete
            showImportResults(imported, skipped, errors);
            return;
        }

        console.log('Importing batch:', startIndex, 'to', startIndex + batch.length);

        $.ajax({
            url: 'ajax/import_patients.php',
            method: 'POST',
            data: JSON.stringify({
                patients: batch,
                skipDuplicates: skipDuplicates,
                updateExisting: updateExisting
            }),
            contentType: 'application/json',
            success: function(response) {
                console.log('Batch response:', response);
                
                if (response.success) {
                    imported += response.imported || 0;
                    skipped += response.skipped || 0;
                    errors += response.errors || 0;
                    
                    processed += batch.length;
                    const progress = Math.round((processed / patients.length) * 100);
                    $('#importProgress').css('width', progress + '%').text(progress + '%');
                    $('#progressText').text(`Processing: ${processed} of ${patients.length} patients`);

                    // Continue with next batch
                    importBatch(startIndex + batchSize);
                } else {
                    console.error('Batch failed:', response.message);
                    errors += batch.length;
                    processed += batch.length;
                    importBatch(startIndex + batchSize);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', status, error);
                errors += batch.length;
                processed += batch.length;
                importBatch(startIndex + batchSize);
            }
        });
    }

    importBatch(0);
}

function showImportResults(imported, skipped, errors) {
    $('.import-progress').hide();
    
    const resultsHtml = `
        <div class="alert alert-success border-0">
            <h5 class="alert-heading">
                <i class="ri-checkbox-circle-line me-2"></i>Import Complete!
            </h5>
            <hr>
            <div class="row text-center mt-3">
                <div class="col-md-4">
                    <div class="p-3">
                        <h3 class="text-success mb-1">${imported}</h3>
                        <p class="mb-0">Successfully Imported</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="p-3">
                        <h3 class="text-warning mb-1">${skipped}</h3>
                        <p class="mb-0">Skipped (Duplicates)</p>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="p-3">
                        <h3 class="text-danger mb-1">${errors}</h3>
                        <p class="mb-0">Errors</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="text-center mt-4">
            <a href="list_patients.php" class="btn btn-primary btn-lg me-2">
                <i class="ri-user-line me-1"></i>View Imported Patients
            </a>
            <button class="btn btn-outline-secondary btn-lg" onclick="location.reload()">
                <i class="ri-refresh-line me-1"></i>Import Another File
            </button>
        </div>
    `;

    $('#importResults').html(resultsHtml).show();
    $('#importActions').hide();

    $('.step[data-step="4"]').addClass('completed');
    
    // Log the import activity
    logImportActivity(imported, skipped, errors);
}

function logImportActivity(imported, skipped, errors) {
    $.ajax({
        url: 'ajax/log_import.php',
        method: 'POST',
        data: JSON.stringify({
            imported: imported,
            skipped: skipped,
            errors: errors,
            filename: $('#fileName').text()
        }),
        contentType: 'application/json'
    });
}