// Interactive features
// TODO: Implement JavaScript functionality for migration dashboard

// Migration Wizard JavaScript
let migrationCurrentStep = 1;
let migrationSelectedSource = null;
let migrationUploadedFiles = [];
let migrationValidationResults = null;
let migrationStatusInterval = null;
let migrationImportResponse = null;

// Initialize tooltips
$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});

// File upload preview
function previewFile(file, container) {
    const reader = new FileReader();
    reader.onload = function(e) {
        const content = e.target.result;
        const rows = content.split('\n').slice(0, 6); // First 5 rows + header

        let html = '<table class="table table-sm"><thead><tr>';
        const headers = rows[0].split(',');
        headers.forEach(header => {
            html += `<th>${header.trim()}</th>`;
        });
        html += '</tr></thead><tbody>';

        for (let i = 1; i < rows.length - 1; i++) {
            const cols = rows[i].split(',');
            html += '<tr>';
            cols.forEach(col => {
                html += `<td>${col.trim()}</td>`;
            });
            html += '</tr>';
        }
        html += '</tbody></table>';

        container.innerHTML = html;
    };
    reader.readAsText(file);
}

// Field mapping interface
function createFieldMapper(fileHeaders, systemFields) {
    let html = '<div class="field-mapper">';
    fileHeaders.forEach(header => {
        html += `
            <div class="row mb-2">
                <div class="col-md-4">
                    <strong>${header}</strong>
                </div>
                <div class="col-md-2 text-center">
                    <i class="fas fa-arrow-right"></i>
                </div>
                <div class="col-md-6">
                    <select class="form-select form-select-sm" name="map[${header}]">
                        <option value="">-- Skip this field --</option>
        `;

        systemFields.forEach(field => {
            const selected = (header.toLowerCase() === field.toLowerCase()) ? 'selected' : '';
            html += `<option value="${field}" ${selected}>${field}</option>`;
        });

        html += `
                    </select>
                </div>
            </div>
        `;
    });
    html += '</div>';
    return html;
}

// Progress bar update
function updateProgress(percent, message) {
    const progressBar = document.getElementById('import-progress');
    const progressMessage = document.getElementById('progress-message');

    if (!progressBar) {
        return;
    }

    const safePercent = Math.max(0, Math.min(100, Number(percent) || 0));
    progressBar.style.width = `${safePercent}%`;
    progressBar.textContent = `${Math.round(safePercent)}%`;
    progressBar.setAttribute('aria-valuenow', safePercent);

    if (progressMessage && message) {
        progressMessage.textContent = message;
    }
}

// Log message to import log
function addLogMessage(message, type = 'info') {
    const logContainer = document.getElementById('import-log');
    if (!logContainer) {
        return;
    }

    const logEntry = document.createElement('div');
    logEntry.className = `log-entry log-${type}`;
    logEntry.innerHTML = `
        <span class="log-time">[${new Date().toLocaleTimeString()}]</span>
        <span class="log-message">${message}</span>
    `;
    logContainer.appendChild(logEntry);
    logContainer.scrollTop = logContainer.scrollHeight;
}

// Download error report
function downloadErrorReport(jobId) {
    window.location.href = `exports/error_report.php?job=${encodeURIComponent(jobId)}`;
}

// Auto-refresh job status
function monitorJob(jobId) {
    if (migrationStatusInterval) {
        clearInterval(migrationStatusInterval);
    }

    migrationStatusInterval = setInterval(function() {
        $.ajax({
            url: `jobs/status.php?job=${encodeURIComponent(jobId)}`,
            dataType: 'json',
            success: function(response) {
                if (!response) {
                    return;
                }

                const status = response.status || '';
                updateProgress(response.progress || 0, response.message || status);

                if (status === 'completed' || status === 'complete') {
                    clearInterval(migrationStatusInterval);
                    addLogMessage('Background import completed successfully.', 'success');
                    showCompletionMessage(response);
                } else if (status === 'failed') {
                    clearInterval(migrationStatusInterval);
                    addLogMessage(response.error || 'Import failed.', 'error');
                    showErrorMessage(response);
                } else {
                    addLogMessage(response.message || `Import status: ${status}`, 'info');
                }
            },
            error: function() {
                clearInterval(migrationStatusInterval);
                addLogMessage('Failed to poll import status.', 'error');
            }
        });
    }, 2000);
}

function setStepState(stepNumber, state) {
    const step = document.getElementById(`step${stepNumber}`);
    if (!step) {
        return;
    }

    step.classList.remove('active', 'completed');
    if (state) {
        step.classList.add(state);
    }
}

function showStep(stepNumber) {
    for (let i = 1; i <= 5; i++) {
        const content = document.getElementById(`step${i}-content`);
        if (content) {
            content.style.display = i === stepNumber ? 'block' : 'none';
        }
        setStepState(i, i < stepNumber ? 'completed' : (i === stepNumber ? 'active' : ''));
    }
    migrationCurrentStep = stepNumber;
}

function validateCurrentStep(stepNumber) {
    if (stepNumber === 1) {
        return migrationSelectedSource !== null;
    }

    if (stepNumber === 2) {
        if (migrationSelectedSource === 'manual') {
            return true;
        }
        return migrationUploadedFiles.length > 0;
    }

    return true;
}

function selectSource(source) {
    migrationSelectedSource = source;
    window.selectedSource = source;

    document.querySelectorAll('.template-card').forEach(card => {
        card.classList.remove('selected');
    });

    const matchedCard = Array.from(document.querySelectorAll('.template-card')).find(card => {
        return card.getAttribute('onclick') && card.getAttribute('onclick').includes(`'${source}'`);
    });
    if (matchedCard) {
        matchedCard.classList.add('selected');
    }

    const continueBtn = document.getElementById('continue-btn');
    if (continueBtn) {
        continueBtn.disabled = false;
    }

    const uploadArea = document.getElementById('uploadArea');
    const manualInfo = document.getElementById('manual-entry-info');
    const validateBtn = document.getElementById('validateBtn');
    const manualBtn = document.getElementById('manualBtn');

    if (source === 'manual') {
        if (uploadArea) uploadArea.style.display = 'none';
        if (manualInfo) manualInfo.style.display = 'block';
        if (validateBtn) validateBtn.style.display = 'none';
        if (manualBtn) manualBtn.style.display = 'inline-block';
    } else {
        if (uploadArea) uploadArea.style.display = 'block';
        if (manualInfo) manualInfo.style.display = 'none';
        if (validateBtn) validateBtn.style.display = 'inline-block';
        if (manualBtn) manualBtn.style.display = 'none';
    }
}

function nextStep(stepNumber) {
    if (!validateCurrentStep(stepNumber)) {
        alert('Please complete the required fields before continuing.');
        return;
    }
    showStep(stepNumber + 1);
}

function prevStep(stepNumber) {
    showStep(stepNumber - 1);
}

function handleFiles(files) {
    migrationUploadedFiles = Array.from(files || []);
    window.uploadedFiles = migrationUploadedFiles;

    const fileList = document.getElementById('fileList');
    const previewContainer = document.getElementById('preview-container');

    if (fileList) {
        fileList.innerHTML = '';
    }

    if (previewContainer) {
        previewContainer.innerHTML = '';
    }

    migrationUploadedFiles.forEach((file, index) => {
        if (fileList) {
            const fileItem = document.createElement('div');
            fileItem.className = 'alert alert-info';
            fileItem.innerHTML = `
                <i class="fas fa-file me-2"></i>${file.name}
                <span class="ms-2 text-muted">(${(file.size / 1024).toFixed(2)} KB)</span>
            `;
            fileList.appendChild(fileItem);
        }

        if (previewContainer && index === 0 && /\.(csv|txt)$/i.test(file.name)) {
            const previewCard = document.createElement('div');
            previewCard.className = 'card mt-3';
            previewCard.innerHTML = `
                <div class="card-header bg-light">
                    <strong>Preview:</strong> ${file.name}
                </div>
                <div class="card-body" id="file-preview-body"></div>
            `;
            previewContainer.innerHTML = '';
            previewContainer.appendChild(previewCard);
            previewFile(file, document.getElementById('file-preview-body'));
        }
    });

    const validateBtn = document.getElementById('validateBtn');
    if (validateBtn) {
        validateBtn.disabled = migrationUploadedFiles.length === 0;
    }
}

function goToManualEntry() {
    window.location.href = 'imports/manual_entry.php';
}

function renderErrorsTable(issues) {
    if (!issues || issues.length === 0) {
        return '';
    }

    let rows = '';
    issues.forEach(issue => {
        rows += `
            <tr>
                <td>${issue.row ?? ''}</td>
                <td>${issue.field ?? ''}</td>
                <td>${issue.type ?? ''}</td>
                <td>${issue.message ?? ''}</td>
            </tr>
        `;
    });

    return `
        <div class="table-responsive mt-3">
            <table class="table table-sm table-bordered">
                <thead>
                    <tr>
                        <th>Row</th>
                        <th>Field</th>
                        <th>Type</th>
                        <th>Message</th>
                    </tr>
                </thead>
                <tbody>${rows}</tbody>
            </table>
        </div>
    `;
}

function displayValidationResults(results) {
    migrationValidationResults = results;
    window.validationResults = results;

    const totalRecords = document.getElementById('total-records');
    const validRecords = document.getElementById('valid-records');
    const warningRecords = document.getElementById('warning-records');
    const errorRecords = document.getElementById('error-records');
    const issuesContainer = document.getElementById('issues-container');
    const suggestionsContainer = document.getElementById('suggestions-container');
    const duplicateWarning = document.getElementById('duplicate-warning');
    const existingWarning = document.getElementById('existing-warning');
    const previewContainer = document.getElementById('preview-container');

    if (totalRecords) totalRecords.textContent = results.total || 0;
    if (validRecords) validRecords.textContent = results.valid || 0;
    if (warningRecords) warningRecords.textContent = results.warnings || 0;
    if (errorRecords) errorRecords.textContent = results.errors || 0;

    if (issuesContainer) {
        if (results.issues && results.issues.length > 0) {
            issuesContainer.innerHTML = '';
            results.issues.forEach(issue => {
                const issueDiv = document.createElement('div');
                issueDiv.className = `validation-issue issue-${issue.type || 'warning'}`;
                issueDiv.innerHTML = `
                    <strong>Row ${issue.row ?? '?'}</strong>: ${issue.message ?? ''}
                    <small class="d-block text-muted">${issue.field ?? ''}</small>
                `;
                issuesContainer.appendChild(issueDiv);
            });
        } else {
            issuesContainer.innerHTML = '<p class="text-success"><i class="fas fa-check-circle me-2"></i>No issues found!</p>';
        }
    }

    if (suggestionsContainer) {
        if (results.suggestions && results.suggestions.length > 0) {
            suggestionsContainer.innerHTML = results.suggestions.map(suggestion => `
                <div class="alert alert-info">
                    <strong>${suggestion.field}:</strong> ${suggestion.message}
                    <div class="small text-muted mt-1">Suggested value: ${suggestion.value}</div>
                </div>
            `).join('');
        } else {
            suggestionsContainer.innerHTML = '<p class="text-muted">No suggestions available</p>';
        }
    }

    if (duplicateWarning) {
        duplicateWarning.innerHTML = results.duplicate_count > 0
            ? `<div class="alert alert-warning"><strong>Duplicates:</strong> ${results.duplicate_count} possible duplicate record(s) found.</div>`
            : '';
    }

    if (existingWarning) {
        existingWarning.innerHTML = results.existing_count > 0
            ? `<div class="alert alert-info"><strong>Existing Records:</strong> ${results.existing_count} record(s) already exist in the database.</div>`
            : '';
    }

    if (previewContainer) {
        previewContainer.innerHTML = renderErrorsTable(results.issues || []);
    }
}

function buildImportFormData() {
    const formData = new FormData();
    formData.append('source', migrationSelectedSource || '');
    migrationUploadedFiles.forEach((file, index) => {
        formData.append(`files[${index}]`, file);
    });
    return formData;
}

function uploadAndValidate() {
    if (!migrationUploadedFiles.length) {
        alert('Please upload at least one file.');
        return;
    }

    const validateBtn = document.getElementById('validateBtn');
    if (validateBtn) {
        validateBtn.disabled = true;
        validateBtn.innerHTML = 'Validating... <i class="fas fa-spinner fa-spin ms-2"></i>';
    }

    $.ajax({
        url: 'imports/csv_import.php?action=validate',
        type: 'POST',
        data: buildImportFormData(),
        processData: false,
        contentType: false,
        dataType: 'json',
        xhr: function() {
            const xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(event) {
                if (event.lengthComputable) {
                    const percent = (event.loaded / event.total) * 100;
                    updateProgress(percent, 'Uploading files for validation...');
                }
            });
            return xhr;
        },
        success: function(response) {
            displayValidationResults(response);
            addLogMessage('Validation complete.', 'success');
            showStep(3);
        },
        error: function(xhr) {
            addLogMessage('Validation failed.', 'error');
            alert(xhr.responseJSON?.message || 'Validation failed. Please check your files and try again.');
        },
        complete: function() {
            if (validateBtn) {
                validateBtn.disabled = migrationUploadedFiles.length === 0;
                validateBtn.innerHTML = 'Validate Data <i class="fas fa-check ms-2"></i>';
            }
        }
    });
}

function showCompletionMessage(response) {
    const importComplete = document.getElementById('import-complete');
    const importSummary = document.getElementById('import-summary');

    if (importComplete) {
        importComplete.style.display = 'block';
    }

    if (importSummary) {
        const imported = response.imported ?? response.successful ?? 0;
        const failed = response.failed ?? 0;
        importSummary.textContent = `Imported ${imported} record(s). Failed: ${failed}.`;
    }
}

function showErrorMessage(response) {
    const importSummary = document.getElementById('import-summary');
    if (importSummary) {
        importSummary.textContent = response.error || response.message || 'Import failed.';
    }
}

function startImport() {
    showStep(5);
    updateProgress(0, 'Starting import...');
    addLogMessage('Starting import...', 'info');

    $.ajax({
        url: 'imports/csv_import.php?action=import',
        type: 'POST',
        data: buildImportFormData(),
        processData: false,
        contentType: false,
        dataType: 'json',
        xhr: function() {
            const xhr = new XMLHttpRequest();
            xhr.upload.addEventListener('progress', function(event) {
                if (event.lengthComputable) {
                    const percent = (event.loaded / event.total) * 100;
                    updateProgress(percent, 'Uploading import payload...');
                }
            });
            return xhr;
        },
        success: function(response) {
            migrationImportResponse = response;
            window.migrationImportResponse = response;

            if (response.details && Array.isArray(response.details)) {
                response.details.forEach(detail => addLogMessage(detail, 'success'));
            }

            if (Array.isArray(response.errors) && response.errors.length > 0) {
                const previewContainer = document.getElementById('preview-container');
                if (previewContainer) {
                    previewContainer.innerHTML = renderErrorsTable(response.errors);
                }
            }

            if (response.job_id) {
                addLogMessage(`Background job created: ${response.job_id}`, 'info');
                monitorJob(response.job_id);
                return;
            }

            updateProgress(100, 'Import complete');
            showCompletionMessage(response);
        },
        error: function(xhr) {
            updateProgress(0, 'Import failed');
            addLogMessage(xhr.responseJSON?.message || 'Import failed.', 'error');
            showErrorMessage({
                error: xhr.responseJSON?.message || 'Import failed.'
            });
        }
    });
}

function finishMigration() {
    window.location.href = '../dashboard.php?migration=complete';
}

function initializeMigrationWizard() {
    showStep(1);

    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');

    if (uploadArea && fileInput) {
        uploadArea.addEventListener('click', function() {
            fileInput.click();
        });

        uploadArea.addEventListener('dragover', function(event) {
            event.preventDefault();
            uploadArea.style.borderColor = '#667eea';
            uploadArea.style.background = '#f8f9fa';
        });

        uploadArea.addEventListener('dragleave', function(event) {
            event.preventDefault();
            uploadArea.style.borderColor = '#dee2e6';
            uploadArea.style.background = 'white';
        });

        uploadArea.addEventListener('drop', function(event) {
            event.preventDefault();
            uploadArea.style.borderColor = '#dee2e6';
            uploadArea.style.background = 'white';
            handleFiles(event.dataTransfer.files);
        });

        fileInput.addEventListener('change', function(event) {
            handleFiles(event.target.files);
        });
    }

    window.selectSource = selectSource;
    window.nextStep = nextStep;
    window.prevStep = prevStep;
    window.handleFiles = handleFiles;
    window.goToManualEntry = goToManualEntry;
    window.uploadAndValidate = uploadAndValidate;
    window.displayValidationResults = displayValidationResults;
    window.startImport = startImport;
    window.finishMigration = finishMigration;
}

window.addEventListener('load', initializeMigrationWizard);
