/**
 * Import method selection and form validation
 */

$(document).ready(() => {
    initImportMethodSelection();
    initFormValidation();
});

/**
 * Initialize import method selection
 */
const initImportMethodSelection = () => {
    $('.import-method-option').on('click', function() {
        const method = $(this).data('method');
        selectImportMethod(method);
    });

    $('input[name="import_method"]').on('change', function() {
        const method = $(this).val();
        selectImportMethod(method);
    });

    const currentMethod = $('input[name="import_method"]:checked').val();
    if (currentMethod) {
        selectImportMethod(currentMethod);
    }
};

/**
 * Select import method and update UI
 */
const selectImportMethod = (method) => {
    $(`input[name="import_method"][value="${method}"]`).prop('checked', true);

    $('.import-method-option').removeClass('selected');
    $(`.import-method-option[data-method="${method}"]`).addClass('selected');

    if (method === 'csv') {
        $('#database-import-section').hide();
        $('#csv-import-section').show();
        updateFormRequirements('csv');
    } else {
        $('#csv-import-section').hide();
        $('#database-import-section').show();
        updateFormRequirements('database');
    }
};

/**
 * Update form field requirements
 */
const updateFormRequirements = (method) => {
    const csvFields = ['#csvFile', '#csvTemplateType'];
    const dbFields = ['#importSource', '#inputDbHost', '#inputDbName', '#inputDbUser', '#inputDbPassword'];

    if (method === 'csv') {
        csvFields.forEach(field => $(field).prop('required', true));
        dbFields.forEach(field => $(field).prop('required', false));
    } else {
        csvFields.forEach(field => $(field).prop('required', false));
        dbFields.forEach(field => $(field).prop('required', true));
    }
};

/**
 * Initialize form validation
 */
const initFormValidation = () => {
    $('#csvFile').on('change', function() {
        clearPreviousErrors(this);
        validateCsvFile(this);
        autoDetectTemplateType(this);
    });

    $('#importAssistForm').on('submit', function(e) {
        if (!validateForm()) {
            e.preventDefault();
            return false;
        }
    });
};

/**
 * Clear previous error messages
 */
const clearPreviousErrors = (fileInput) => {
    const $fileGroup = $(fileInput).closest('.form-group');
    $(fileInput).removeClass('has-error');
    $fileGroup.find('.file-error').remove();
};

/**
 * Validate CSV file
 */
const validateCsvFile = (fileInput) => {
    const file = fileInput.files[0];
    if (!file) return true;

    const fileName = file.name.toLowerCase();
    if (!fileName.endsWith('.csv')) {
        showFileError(fileInput, 'You must upload a valid CSV file.');
        return false;
    }

    return true;
};

/**
 * Show file error message
 */
const showFileError = (fileInput, message) => {
    const $fileGroup = $(fileInput).closest('.form-group');
    const $helpBlock = $fileGroup.find('.help-block');

    clearPreviousErrors(fileInput);

    $(fileInput).addClass('has-error');
    $helpBlock.append(`<div class="text-danger file-error">${message}</div>`);
};

/**
 * Auto-detect template type from filename
 */
const autoDetectTemplateType = (fileInput) => {
    const file = fileInput.files[0];
    if (!file) return;

    const fileName = file.name.toLowerCase();
    const parts = fileName.split('.');

    // Look for pattern: name.template.csv
    if (parts.length >= 3 && parts[parts.length - 1] === 'csv') {
        const templateType = parts[parts.length - 2];
        const $templateSelect = $('#csvTemplateType');
        const $option = $templateSelect.find(`option[value="${templateType}"]`);

        if ($option.length > 0) {
            $templateSelect.val(templateType);

            const $helpBlock = $templateSelect.closest('.form-group').find('.help-block');
            $helpBlock.find('.auto-detect-message').remove();
            $helpBlock.append(
                '<div class="text-success auto-detect-message">' +
                    '<small><i class="fal fa-check"></i> Template Type Detected: ' + templateType + '</small>' +
                '</div>'
            );
        }
    }
};

/**
 * Validate form before submission
 */
const validateForm = () => {
    const method = $('input[name="import_method"]:checked').val();

    if (method === 'csv') {
        const csvFile = $('#csvFile')[0].files[0];
        const templateType = $('#csvTemplateType').val();

        if (!csvFile || !templateType) {
            return false;
        }

        return validateCsvFile($('#csvFile')[0]);
    } else {
        const importSource = $('#importSource').val();
        const dbHost = $('#inputDbHost').val();
        const dbName = $('#inputDbName').val();
        const dbUser = $('#inputDbUser').val();

        return !!(importSource && dbHost && dbName && dbUser);
    }
};
