/**
 * HA Rule Manager
 * Handles dynamic management of High Availability rules for both v8 and v9 Proxmox
 */
var HaRuleManager = {
    dataCenterId: null,
    version: null,

    /**
     * Initialize the HA Rule Manager
     * @param {string} dataCenterId - UUID of the data center
     * @param {string} version - 'v8' or 'v9'
     */
    init: function(dataCenterId, version) {
        this.dataCenterId = dataCenterId;
        this.version = version || 'v8';
        this.bindEvents();
        this.loadRules();
    },

    /**
     * Bind UI events
     */
    bindEvents: function() {
        var self = this;

        // Enable/Disable HA toggle
        $('#enable-ha-toggle').on('change', function() {
            var isEnabled = $(this).is(':checked');
            self.toggleHA(isEnabled);
        });

        // Add OS rule button
        $(document).on('click', '.add-os-rule', function(e) {
            e.preventDefault();
            self.showOsRuleForm();
        });

        // Add VDC rule button
        $(document).on('click', '.add-vdc-rule', function(e) {
            e.preventDefault();
            var vdcId = $(this).data('vdc-id');
            self.showVdcRuleForm(vdcId);
        });

        // Edit rule button
        $(document).on('click', '.edit-rule', function(e) {
            e.preventDefault();
            var ruleId = $(this).data('rule-id');
            var ruleType = $(this).data('rule-type');
            self.editRule(ruleId, ruleType);
        });

        // Delete rule button
        $(document).on('click', '.delete-rule', function(e) {
            e.preventDefault();
            var ruleId = $(this).data('rule-id');
            if (confirm('Are you sure you want to delete this rule?')) {
                self.deleteRule(ruleId);
            }
        });

        // Sync from Proxmox button
        $(document).on('click', '.sync-from-proxmox', function(e) {
            e.preventDefault();
            self.syncFromProxmox();
        });
    },

    /**
     * Load and display current rules
     */
    loadRules: function() {
        var self = this;

        $.ajax({
            url: '/ha-affinity-rule/list-rules',
            type: 'GET',
            data: {
                data_center_id: self.dataCenterId
            },
            success: function(response) {
                if (response.status === 'success') {
                    self.displayRules(response.data);
                }
            },
            error: function() {
                toastr.error('Failed to load HA rules');
            }
        });
    },

    /**
     * Display rules in the UI
     * @param {Object} data - Rules data
     */
    displayRules: function(data) {
        // Update OS rules section
        if (data.osRules && data.osRules.length > 0) {
            var osHtml = this.renderOsRules(data.osRules);
            $('#os-rules-container').html(osHtml);
        }

        // Update VDC rules section
        if (data.vdcRules && data.vdcRules.length > 0) {
            var vdcHtml = this.renderVdcRules(data.vdcRules);
            $('#vdc-rules-container').html(vdcHtml);
        }

        // Update default rule display
        if (data.defaultRule) {
            $('#default-rule-info').html(this.renderDefaultRule(data.defaultRule));
        }
    },

    /**
     * Render OS rules HTML
     * @param {Array} rules - OS rules array
     * @returns {string} HTML string
     */
    renderOsRules: function(rules) {
        var html = '<div class="list-group">';

        rules.forEach(function(rule) {
            html += '<div class="list-group-item">';
            html += '<div class="d-flex justify-content-between align-items-center">';
            html += '<div>';
            html += '<strong>' + rule.osFamily + '</strong>';

            if (this.version === 'v9') {
                html += ' - <span class="badge bg-info">' + rule.ruleType + '</span>';
                if (rule.nodes && rule.nodes.length > 0) {
                    html += ' <small class="text-muted">(' + rule.nodes.join(', ') + ')</small>';
                }
            } else {
                html += ' - <span class="badge bg-secondary">' + rule.groupName + '</span>';
            }

            if (rule.isEnforced) {
                html += ' <span class="badge bg-warning">Enforced</span>';
            }

            html += '</div>';
            html += '<div class="btn-group btn-group-sm">';
            html += '<button class="btn btn-outline-primary edit-rule" data-rule-id="' + rule.id + '" data-rule-type="os">';
            html += '<i class="ri-edit-line"></i>';
            html += '</button>';
            html += '<button class="btn btn-outline-danger delete-rule" data-rule-id="' + rule.id + '">';
            html += '<i class="ri-delete-bin-line"></i>';
            html += '</button>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
        }.bind(this));

        html += '</div>';
        return html;
    },

    /**
     * Render VDC rules HTML
     * @param {Array} rules - VDC rules array
     * @returns {string} HTML string
     */
    renderVdcRules: function(rules) {
        var html = '<div class="list-group">';

        rules.forEach(function(rule) {
            html += '<div class="list-group-item">';
            html += '<div class="d-flex justify-content-between align-items-center">';
            html += '<div>';
            html += '<strong>' + rule.vdcName + '</strong>';

            if (this.version === 'v9') {
                html += ' - <span class="badge bg-info">' + rule.ruleType + '</span>';
                if (rule.nodes && rule.nodes.length > 0) {
                    html += ' <small class="text-muted">(' + rule.nodes.join(', ') + ')</small>';
                }
            } else {
                html += ' - <span class="badge bg-secondary">' + rule.groupName + '</span>';
            }

            if (rule.isEnforced) {
                html += ' <span class="badge bg-warning">Enforced</span>';
            }

            html += '</div>';
            html += '<div class="btn-group btn-group-sm">';
            html += '<button class="btn btn-outline-primary edit-rule" data-rule-id="' + rule.id + '" data-rule-type="vdc">';
            html += '<i class="ri-edit-line"></i>';
            html += '</button>';
            html += '<button class="btn btn-outline-danger delete-rule" data-rule-id="' + rule.id + '">';
            html += '<i class="ri-delete-bin-line"></i>';
            html += '</button>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
        }.bind(this));

        html += '</div>';
        return html;
    },

    /**
     * Render default rule info
     * @param {Object} rule - Default rule object
     * @returns {string} HTML string
     */
    renderDefaultRule: function(rule) {
        var html = '<div class="alert alert-info">';
        html += '<i class="ri-information-line"></i> ';

        if (this.version === 'v9') {
            html += 'Default rule: <strong>' + rule.ruleType + '</strong>';
            if (rule.nodes && rule.nodes.length > 0) {
                html += ' across nodes: ' + rule.nodes.join(', ');
            }
        } else {
            html += 'Default placement group: <strong>' + rule.groupName + '</strong>';
        }

        html += '</div>';
        return html;
    },

    /**
     * Toggle HA on/off
     * @param {boolean} enable - Enable or disable HA
     */
    toggleHA: function(enable) {
        var self = this;
        var action = enable ? 'enable-datacenter-ha' : 'disable-datacenter-ha';

        $.ajax({
            url: '/ha-affinity-rule/' + action,
            type: 'POST',
            data: {
                data_center_id: self.dataCenterId,
                _csrf: yii.getCsrfToken()
            },
            success: function(response) {
                if (response.status === 'success') {
                    toastr.success(response.message);
                    self.loadRules();
                } else {
                    toastr.error(response.message || 'Failed to toggle HA');
                    // Revert toggle state
                    $('#enable-ha-toggle').prop('checked', !enable);
                }
            },
            error: function() {
                toastr.error('Failed to toggle HA');
                // Revert toggle state
                $('#enable-ha-toggle').prop('checked', !enable);
            }
        });
    },

    /**
     * Show OS rule form in modal
     */
    showOsRuleForm: function() {
        var self = this;

        $.ajax({
            url: '/ha-affinity-rule/os-rule-form',
            type: 'GET',
            data: {
                data_center_id: self.dataCenterId
            },
            success: function(html) {
                $('#modal .modal-content').html(html);
                $('#modal').modal('show');
            },
            error: function() {
                toastr.error('Failed to load form');
            }
        });
    },

    /**
     * Show VDC rule form in modal
     * @param {string} vdcId - Virtual Data Center ID
     */
    showVdcRuleForm: function(vdcId) {
        var self = this;

        $.ajax({
            url: '/ha-affinity-rule/vdc-rule-form',
            type: 'GET',
            data: {
                data_center_id: self.dataCenterId,
                vdc_id: vdcId
            },
            success: function(html) {
                $('#modal .modal-content').html(html);
                $('#modal').modal('show');
            },
            error: function() {
                toastr.error('Failed to load form');
            }
        });
    },

    /**
     * Edit existing rule
     * @param {string} ruleId - Rule ID
     * @param {string} ruleType - 'os' or 'vdc'
     */
    editRule: function(ruleId, ruleType) {
        var self = this;
        var action = ruleType === 'os' ? 'os-rule-form' : 'vdc-rule-form';

        $.ajax({
            url: '/ha-affinity-rule/' + action,
            type: 'GET',
            data: {
                data_center_id: self.dataCenterId,
                id: ruleId
            },
            success: function(html) {
                $('#modal .modal-content').html(html);
                $('#modal').modal('show');
            },
            error: function() {
                toastr.error('Failed to load form');
            }
        });
    },

    /**
     * Delete rule
     * @param {string} ruleId - Rule ID
     */
    deleteRule: function(ruleId) {
        var self = this;

        $.ajax({
            url: '/ha-affinity-rule/delete',
            type: 'POST',
            data: {
                id: ruleId,
                _csrf: yii.getCsrfToken()
            },
            success: function(response) {
                if (response.status === 'success') {
                    toastr.success('Rule deleted successfully');
                    self.loadRules();
                } else {
                    toastr.error(response.message || 'Failed to delete rule');
                }
            },
            error: function() {
                toastr.error('Failed to delete rule');
            }
        });
    },

    /**
     * Sync rules from Proxmox
     */
    syncFromProxmox: function() {
        var self = this;

        $.ajax({
            url: '/ha-affinity-rule/sync-from-proxmox',
            type: 'POST',
            data: {
                data_center_id: self.dataCenterId,
                _csrf: yii.getCsrfToken()
            },
            beforeSend: function() {
                toastr.info('Syncing rules from Proxmox...');
            },
            success: function(response) {
                if (response.status === 'success') {
                    toastr.success('Rules synced successfully');
                    self.loadRules();
                } else {
                    toastr.error(response.message || 'Failed to sync rules');
                }
            },
            error: function() {
                toastr.error('Failed to sync rules');
            }
        });
    }
};

// Auto-initialize if data attributes are present
$(document).ready(function() {
    var $container = $('#ha-rule-manager');
    if ($container.length > 0) {
        var dataCenterId = $container.data('datacenter-id');
        var version = $container.data('version');

        if (dataCenterId) {
            HaRuleManager.init(dataCenterId, version);
        }
    }
});