<?php

namespace PloverCRM\Modules\AdminSettings\Tabs;

/**
 * Module Manager Tab
 * 
 * Handles module management - enable/disable modules
 */
class ModuleManagerTab
{
    /**
     * Register settings
     */
    public function register(): void
    {
        add_action('admin_init', [$this, 'registerSettings']);
        
        // Register AJAX handlers
        add_action('wp_ajax_plover_crm_toggle_module', [$this, 'handleToggleModule']);
        add_action('wp_ajax_plover_crm_install_module', [$this, 'handleInstallModule']);
    }

    /**
     * Register settings fields
     */
    public function registerSettings(): void
    {
        register_setting('plover_crm_module_manager_settings', 'plover_crm_disabled_modules');

        add_settings_section(
            'plover_crm_module_manager_section',
            'Module Management',
            [$this, 'renderSectionDescription'],
            'plover_crm_module_manager'
        );

        add_settings_field(
            'plover_crm_installed_modules',
            'Installed Modules',
            [$this, 'renderInstalledModules'],
            'plover_crm_module_manager',
            'plover_crm_module_manager_section'
        );

        add_settings_field(
            'plover_crm_available_modules',
            'Available Modules',
            [$this, 'renderAvailableModules'],
            'plover_crm_module_manager',
            'plover_crm_module_manager_section'
        );
    }

    /**
     * Render section description
     */
    public function renderSectionDescription(): void
    {
        echo '<p>Manage your installed modules. Enable or disable modules as needed.</p>';
    }

    /**
     * Render installed modules
     */
    public function renderInstalledModules(): void
    {
        $plugin = \PloverCRM\Core\Plugin::getInstance();
        $moduleManager = $plugin->getModuleManager();
        $disabledModules = get_option('plover_crm_disabled_modules', []);

        // Get all discovered modules (including disabled ones)
        $plugin = \PloverCRM\Core\Plugin::getInstance();
        $allModules = $plugin->getAllDiscoveredModules();

        $modules = [];
        foreach ($allModules as $moduleId => $moduleInstance) {
            $metadata = $moduleInstance->getMetadata();

            // Skip required modules (like admin_settings)
            if (!empty($metadata['required'])) {
                continue;
            }

            $modules[$moduleId] = $metadata;
        }

        ?>
        <style>
            .plvcrm-modules-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
                gap: 20px;
                margin-top: 20px;
            }

            .plvcrm-module-card {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 20px;
                transition: box-shadow 0.3s ease;
            }

            .plvcrm-module-card:hover {
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }

            .plvcrm-module-card.disabled {
                opacity: 0.6;
                background: #f5f5f5;
            }

            .plvcrm-module-header {
                margin-bottom: 12px;
            }

            .plvcrm-module-title {
            }

            .plvcrm-module-title h3 {
                margin: 0;
                font-size: 16px;
                color: #333;
            }

            .plvcrm-module-status {
                display: inline-block;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 11px;
                font-weight: 600;
                text-transform: uppercase;
                margin-top: 0.5rem;
            }

            .plvcrm-module-status.active {
                background: #d4edda;
                color: #155724;
            }

            .plvcrm-module-status.inactive {
                background: #f8d7da;
                color: #721c24;
            }

            .plvcrm-module-status.required {
                background: #cce5ff;
                color: #004085;
            }

            .plvcrm-module-description {
                color: #666;
                font-size: 13px;
                line-height: 1.5;
                margin-bottom: 15px;
            }

            .plvcrm-module-actions {
                display: flex;
                gap: 10px;
            }

            .plvcrm-toggle-module-btn {
                flex: 1;
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 13px;
                font-weight: 600;
                transition: all 0.3s ease;
            }

            .plvcrm-toggle-module-btn.enable {
                background: #28a745;
                color: white;
            }

            .plvcrm-toggle-module-btn.enable:hover {
                background: #218838;
            }

            .plvcrm-toggle-module-btn.disable {
                background: #dc3545;
                color: white;
            }

            .plvcrm-toggle-module-btn.disable:hover {
                background: #c82333;
            }

            .plvcrm-toggle-module-btn:disabled {
                opacity: 0.5;
                cursor: not-allowed;
            }

            .plvcrm-module-notice {
                margin-top: 20px;
                padding: 12px;
                background: #fff3cd;
                border: 1px solid #ffeaa7;
                border-radius: 4px;
                color: #856404;
                font-size: 13px;
            }
        </style>

        <div class="plvcrm-modules-grid">
            <?php foreach ($modules as $moduleId => $moduleInfo): ?>
                <?php
                $isDisabled = in_array($moduleId, $disabledModules);
                $isRequired = $moduleInfo['required'];
                $cardClass = $isDisabled ? 'plvcrm-module-card disabled' : 'plvcrm-module-card';
                ?>
                <div class="<?php echo esc_attr($cardClass); ?>" data-module-id="<?php echo esc_attr($moduleId); ?>">
                    <div class="plvcrm-module-header">
                        <div class="plvcrm-module-title">
                            <h3><?php echo esc_html($moduleInfo['name']); ?></h3>
                            <?php if ($isRequired): ?>
                                <span class="plvcrm-module-status required">Required</span>
                            <?php elseif ($isDisabled): ?>
                                <span class="plvcrm-module-status inactive">Inactive</span>
                            <?php else: ?>
                                <span class="plvcrm-module-status active">Active</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="plvcrm-module-description">
                        <?php echo esc_html($moduleInfo['description']); ?>
                    </div>
                    <div class="plvcrm-module-actions">
                        <?php if (!$isRequired): ?>
                            <button 
                                type="button" 
                                class="plvcrm-toggle-module-btn <?php echo $isDisabled ? 'enable' : 'disable'; ?>"
                                onclick="ploverToggleModule('<?php echo esc_js($moduleId); ?>', <?php echo $isDisabled ? 'true' : 'false'; ?>)"
                            >
                                <?php echo $isDisabled ? 'Enable Module' : 'Disable Module'; ?>
                            </button>
                        <?php else: ?>
                            <button type="button" class="plvcrm-toggle-module-btn" disabled>
                                Required Module
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="plvcrm-module-notice">
            <strong>Note:</strong> Changes will take effect after page reload. Required modules cannot be disabled.
        </div>

        <style>
            .plvcrm-toast-notification {
                position: fixed;
                top: 32px;
                right: 20px;
                background: #fff;
                border-left: 4px solid #46b450;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                padding: 16px 20px;
                border-radius: 4px;
                z-index: 999999;
                animation: ploverSlideIn 0.3s ease-out;
                max-width: 400px;
            }

            .plvcrm-toast-notification.error {
                border-left-color: #dc3232;
            }

            .plvcrm-toast-notification p {
                margin: 0;
                font-size: 14px;
                color: #333;
            }

            @keyframes ploverSlideIn {
                from {
                    transform: translateX(400px);
                    opacity: 0;
                }
                to {
                    transform: translateX(0);
                    opacity: 1;
                }
            }

            @keyframes ploverSlideOut {
                from {
                    transform: translateX(0);
                    opacity: 1;
                }
                to {
                    transform: translateX(400px);
                    opacity: 0;
                }
            }
        </style>

        <script>
            function ploverShowToast(message, type = 'success') {
                // Remove any existing toast
                const existingToast = document.querySelector('.plvcrm-toast-notification');
                if (existingToast) {
                    existingToast.remove();
                }

                // Create new toast
                const toast = document.createElement('div');
                toast.className = 'plvcrm-toast-notification' + (type === 'error' ? ' error' : '');
                toast.innerHTML = '<p>' + message + '</p>';
                document.body.appendChild(toast);

                // Auto remove after animation
                setTimeout(function() {
                    toast.style.animation = 'ploverSlideOut 0.3s ease-out';
                    setTimeout(function() {
                        toast.remove();
                    }, 300);
                }, 2000);
            }

            function ploverToggleModule(moduleId, enable) {
                const button = event.target;
                const card = button.closest('.plvcrm-module-card');
                
                button.disabled = true;
                button.textContent = enable ? 'Enabling...' : 'Disabling...';

                jQuery.ajax({
                    url: ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'plover_crm_toggle_module',
                        nonce: '<?php echo wp_create_nonce('plover_crm_toggle_module'); ?>',
                        module_id: moduleId,
                        enable: enable
                    },
                    success: function(response) {
                        if (response.success) {
                            // Show toast notification
                            ploverShowToast(response.data.message, 'success');
                            
                            // Reload page after 1 second
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            ploverShowToast(response.data.message || 'Failed to toggle module', 'error');
                            button.disabled = false;
                            button.textContent = enable ? 'Enable Module' : 'Disable Module';
                        }
                    },
                    error: function() {
                        ploverShowToast('Error toggling module', 'error');
                        button.disabled = false;
                        button.textContent = enable ? 'Enable Module' : 'Disable Module';
                    }
                });
            }
        </script>
        <?php
    }

    /**
     * Handle toggle module AJAX request
     */
    public function handleToggleModule(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'plover_crm_toggle_module')) {
            wp_send_json_error(['message' => 'Invalid nonce']);
            return;
        }

        $moduleId = sanitize_text_field($_POST['module_id'] ?? '');
        $enable = filter_var($_POST['enable'] ?? false, FILTER_VALIDATE_BOOLEAN);

        if (empty($moduleId)) {
            wp_send_json_error(['message' => 'Invalid module ID']);
            return;
        }

        $disabledModules = get_option('plover_crm_disabled_modules', []);

        if ($enable) {
            // Remove from disabled list
            $disabledModules = array_diff($disabledModules, [$moduleId]);
            $message = 'Module enabled successfully';
        } else {
            // Check if this is a CRM module
            $crmModules = ['fluent_crm', 'native_crm'];
            
            if (in_array($moduleId, $crmModules)) {
                // Check if disabling this would leave no CRM modules enabled
                $otherCRMModules = array_diff($crmModules, [$moduleId]);
                $allCRMDisabled = true;
                
                foreach ($otherCRMModules as $otherCRM) {
                    if (!in_array($otherCRM, $disabledModules)) {
                        $allCRMDisabled = false;
                        break;
                    }
                }
                
                if ($allCRMDisabled) {
                    wp_send_json_error([
                        'message' => 'Cannot disable all CRM modules. At least one CRM module must be enabled. Please enable another CRM module first.'
                    ]);
                    return;
                }
            }
            
            // Add to disabled list
            if (!in_array($moduleId, $disabledModules)) {
                $disabledModules[] = $moduleId;
            }
            $message = 'Module disabled successfully';
        }

        update_option('plover_crm_disabled_modules', array_values($disabledModules));

        wp_send_json_success(['message' => $message]);
    }

    /**
     * Render available modules
     */
    public function renderAvailableModules(): void
    {
        $installer = new \PloverCRM\Core\ModuleInstaller();
        $availableModules = $installer->getAvailableModules();

        if (is_wp_error($availableModules)) {
            echo '<p style="color: #dc3545;">Failed to fetch available modules: ' . esc_html($availableModules->get_error_message()) . '</p>';
            return;
        }

        // Get installed modules
        $plugin = \PloverCRM\Core\Plugin::getInstance();
        $installedModules = array_keys($plugin->getAllDiscoveredModules());

        ?>
        <div class="plvcrm-modules-grid" style="margin-top: 30px;">
            <?php foreach ($availableModules as $module): ?>
                <?php
                $isInstalled = in_array($module['slug'], $installedModules);
                $needsUpdate = $isInstalled && $installer->needsUpdate($module['slug'], $module['version']);
                ?>
                <div class="plvcrm-module-card" data-module-slug="<?php echo esc_attr($module['slug']); ?>">
                    <div class="plvcrm-module-header">
                        <div class="plvcrm-module-title">
                            <h3><?php echo esc_html($module['name']); ?></h3>
                            <?php if ($isInstalled): ?>
                                <?php if ($needsUpdate): ?>
                                    <span class="plvcrm-module-status" style="background: #fff3cd; color: #856404;">Update Available</span>
                                <?php else: ?>
                                    <span class="plvcrm-module-status active">Installed</span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="plvcrm-module-status" style="background: #e7f3ff; color: #004085;">Available</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="plvcrm-module-description">
                        <?php echo esc_html($module['description']); ?>
                    </div>
                    <div class="plvcrm-module-meta" style="font-size: 12px; color: #666; margin-bottom: 15px;">
                        Version: <?php echo esc_html($module['version']); ?>
                    </div>
                    <div class="plvcrm-module-actions">
                        <?php if ($isInstalled && !$needsUpdate): ?>
                            <button type="button" class="plvcrm-toggle-module-btn" disabled style="background: #6c757d;">
                                Already Installed
                            </button>
                        <?php else: ?>
                            <button 
                                type="button" 
                                class="plvcrm-toggle-module-btn enable"
                                onclick="ploverInstallModule('<?php echo esc_js($module['slug']); ?>', '<?php echo esc_js($module['download_url']); ?>', <?php echo $needsUpdate ? 'true' : 'false'; ?>)"
                            >
                                <?php echo $needsUpdate ? 'Update Module' : 'Install Module'; ?>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <script>
            function ploverInstallModule(slug, downloadUrl, isUpdate) {
                const button = event.target;
                const card = button.closest('.plvcrm-module-card');
                
                button.disabled = true;
                button.textContent = isUpdate ? 'Updating...' : 'Installing...';

                jQuery.ajax({
                    url: ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'plover_crm_install_module',
                        nonce: '<?php echo wp_create_nonce('plover_crm_install_module'); ?>',
                        slug: slug,
                        download_url: downloadUrl
                    },
                    success: function(response) {
                        if (response.success) {
                            ploverShowToast(response.data.message, 'success');
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            ploverShowToast(response.data.message || 'Installation failed', 'error');
                            button.disabled = false;
                            button.textContent = isUpdate ? 'Update Module' : 'Install Module';
                        }
                    },
                    error: function() {
                        ploverShowToast('Error installing module', 'error');
                        button.disabled = false;
                        button.textContent = isUpdate ? 'Update Module' : 'Install Module';
                    }
                });
            }
        </script>
        <?php
    }

    /**
     * Handle install module AJAX request
     */
    public function handleInstallModule(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'plover_crm_install_module')) {
            wp_send_json_error(['message' => 'Invalid nonce']);
            return;
        }

        $slug = sanitize_text_field($_POST['slug'] ?? '');
        $downloadUrl = esc_url_raw($_POST['download_url'] ?? '');

        if (empty($slug) || empty($downloadUrl)) {
            wp_send_json_error(['message' => 'Invalid parameters']);
            return;
        }

        $installer = new \PloverCRM\Core\ModuleInstaller();
        $result = $installer->installModule($slug, $downloadUrl);

        if ($result['success']) {
            wp_send_json_success(['message' => $result['message']]);
        } else {
            wp_send_json_error(['message' => $result['message']]);
        }
    }
}
