<?php

namespace _121Digital\Connect\Admin;

use _121Digital\Connect\Admin\Services\NoticeService;
use _121Digital\Connect\Admin\Themes\Services\ThemesService;
use _121Digital\Connect\User\UserRoles;

class AdminThemes
{
    public function register(): void
    {
        // Use admin_init instead of admin_notices to bypass blocking
        add_action('admin_init', [ $this, 'maybeRenderThemeHelperNotice' ]);
        add_action('wp_ajax_install_builderpro_theme', [ $this, 'handleInstallBuilderProTheme' ]);
        add_action('wp_ajax_activate_builderpro_theme', [ $this, 'handleActivateBuilderProTheme' ]);
        add_action('wp_ajax_cleanup_orphaned_themes', [ $this, 'handleCleanupOrphanedThemes' ]);
        add_action('admin_enqueue_scripts', [ $this, 'enqueueAdminScripts' ]);
    }

    public function enqueueAdminScripts($hook): void
    {
        // Only load on themes page
        if ($hook !== 'themes.php') {
            return;
        }

        // Only load for administrators
        if (!UserRoles::isContextAdministrator()) {
            return;
        }

        wp_enqueue_script('jquery');
        wp_localize_script('jquery', 'builderProThemeAjax', [
          'ajaxurl' => admin_url('admin-ajax.php'),
          'installNonce' => wp_create_nonce('install_builderpro_theme'),
          'activateNonce' => wp_create_nonce('activate_builderpro_theme'),
          'cleanupNonce' => wp_create_nonce('cleanup_orphaned_themes'),
          'messages' => [
            'installing' => __('Installing...', 'reg121-connect'),
            'activating' => __('Activating...', 'reg121-connect'),
            'cleaning' => __('Cleaning up...', 'reg121-connect'),
            'installed' => __('Installed Successfully!', 'reg121-connect'),
            'activated' => __('Activated Successfully!', 'reg121-connect'),
            'cleaned' => __('Cleanup Complete!', 'reg121-connect'),
            'installFailed' => __('Install Failed - Try Again', 'reg121-connect'),
            'activateFailed' => __('Activation Failed - Try Again', 'reg121-connect'),
            'cleanupFailed' => __('Cleanup Failed - Try Again', 'reg121-connect'),
            'installError' => __('Installation failed: ', 'reg121-connect'),
            'activateError' => __('Activation failed: ', 'reg121-connect'),
            'cleanupError' => __('Cleanup failed: ', 'reg121-connect'),
            'genericError' => __('Operation failed. Please try again.', 'reg121-connect')
          ]
        ]);
    }

    public function maybeRenderThemeHelperNotice(): void
    {
        // only render on the themes admin page...
        $currentScreen = get_current_screen();
        if ($currentScreen && $currentScreen->id !== 'themes') {
            return;
        }

        // only render to system admins...
        if (!UserRoles::isContextAdministrator()) {
            return;
        }

        // Hook into admin_notices with protected output (priority 10 to render early, before NoticeService)
        add_action('admin_notices', [$this, 'renderProtectedThemeNotice'], 10);
    }

    public function renderProtectedThemeNotice(): void
    {
        // Only render on themes page
        $currentScreen = get_current_screen();
        if (!$currentScreen || $currentScreen->id !== 'themes') {
            return;
        }

        // only render to system admins...
        if (!UserRoles::isContextAdministrator()) {
            return;
        }

        // Check BuilderPro Base Theme status
        $isBuilderProInstalled = ThemesService::builderProBaseThemeIsInstalled();
        $isBuilderProActive = ThemesService::currentThemeIsBuilderProBaseTheme();

        // Show install notice if BuilderPro is not installed
        if (!$isBuilderProInstalled) {
            ?>
          <div class="notice notice-warning is-dismissible connect-121-notice">
              <p>
                <?php esc_html_e('For optimal performance with REG121 Connect, please install and activate the "BuilderPro Base Theme".', 'reg121-connect'); ?>
              </p>
              <p style="margin: 10px 0;">
                <label>
                  <input type="checkbox" id="remove-other-themes" checked> 
                  <?php esc_html_e('Remove all other themes after installation (Recommended)', 'reg121-connect'); ?>
                </label>
                <br><small style="color: #666;">
                  <?php esc_html_e('This will clean up your installation by removing any conflicting themes.', 'reg121-connect'); ?>
                </small>
              </p>
              <p>
                <button class="button button-primary" id="install-builderpro-theme">
                  <?php esc_html_e('Install BuilderPro Base Theme', 'reg121-connect'); ?>
                </button>
                <a href="<?php echo esc_url(admin_url('themes.php')); ?>" class="button button-secondary">
                  <?php esc_html_e('Browse Themes', 'reg121-connect'); ?>
                </a>
                <button class="button button-secondary" id="cleanup-orphaned-themes" style="margin-left: 10px;">
                  <?php esc_html_e('Clean Up Orphaned Themes', 'reg121-connect'); ?>
                </button>
              </p>
          </div>
          <?php
            $this->renderThemeScripts();
            return;
        }

        // Show activate notice if BuilderPro is installed but not active
        if ($isBuilderProInstalled && !$isBuilderProActive) {
            ?>
          <div class="notice notice-info is-dismissible connect-121-notice">
              <p>
                <?php esc_html_e('For optimal performance with REG121 Connect, please activate the "BuilderPro Base Theme".', 'reg121-connect'); ?>
              </p>
              <p>
                <button class="button button-primary" id="activate-builderpro-theme">
                  <?php esc_html_e('Activate BuilderPro Base Theme', 'reg121-connect'); ?>
                </button>
                <a href="<?php echo esc_url(admin_url('themes.php')); ?>" class="button button-secondary">
                  <?php esc_html_e('View All Themes', 'reg121-connect'); ?>
                </a>
                <button class="button button-secondary" id="cleanup-orphaned-themes" style="margin-left: 10px;">
                  <?php esc_html_e('Clean Up Orphaned Themes', 'reg121-connect'); ?>
                </button>
              </p>
          </div>
          <?php
            $this->renderThemeScripts();
            return;
        }

        // Show cleanup-only notice if BuilderPro is active (or always show cleanup option)
        ?>
        <div class="notice notice-success is-dismissible connect-121-notice">
            <p>
              <strong><?php esc_html_e('REG121 Connect Theme Management', 'reg121-connect'); ?></strong><br>
              <?php esc_html_e('If you see themes listed that don\'t actually exist in your filesystem, you can clean up orphaned theme references.', 'reg121-connect'); ?>
            </p>
            <p>
              <button class="button button-secondary" id="cleanup-orphaned-themes">
                <?php esc_html_e('Clean Up Orphaned Themes', 'reg121-connect'); ?>
              </button>
            </p>
        </div>
        <?php
        $this->renderThemeScripts();
    }

    private function renderThemeScripts(): void
    {
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
          var installInProgress = false;
          var activateInProgress = false;
          var cleanupInProgress = false;
          
          // Install theme handler (use .off() to prevent multiple bindings)
          $('#install-builderpro-theme').off('click').on('click', function(e) {
            e.preventDefault();
            var button = $(this);
            
            // Prevent multiple installations
            if (installInProgress) {
              console.log('Installation already in progress, ignoring click');
              return;
            }
            
            // Get checkbox value
            var removeOtherThemes = $('#remove-other-themes').is(':checked');
            
            installInProgress = true;
            button.prop('disabled', true).text(builderProThemeAjax.messages.installing);
            
            $.ajax({
              url: builderProThemeAjax.ajaxurl,
              type: 'POST',
              timeout: 30000, // 30 second timeout
              data: {
                action: 'install_builderpro_theme',
                nonce: builderProThemeAjax.installNonce,
                remove_other_themes: removeOtherThemes ? '1' : '0'
              },
              success: function(response) {
                console.log('AJAX Response:', response);
                if (response && response.success) {
                  button.text(builderProThemeAjax.messages.installed);
                  setTimeout(function() {
                    location.reload();
                  }, 1000);
                } else {
                  installInProgress = false;
                  button.prop('disabled', false).text(builderProThemeAjax.messages.installFailed);
                  alert(builderProThemeAjax.messages.installError + (response && response.data ? response.data : 'Unknown error'));
                }
              },
              error: function(xhr, status, error) {
                installInProgress = false;
                console.log('AJAX Error Details:', {
                  status: status,
                  error: error,
                  responseText: xhr.responseText
                });
                
                // Try to parse JSON from response text if it exists
                try {
                  var jsonResponse = JSON.parse(xhr.responseText);
                  if (jsonResponse && jsonResponse.success) {
                    button.text(builderProThemeAjax.messages.installed);
                    setTimeout(function() {
                      location.reload();
                    }, 1000);
                    return;
                  }
                } catch (e) {
                  // Not valid JSON, continue with error handling
                }
                
                button.prop('disabled', false).text(builderProThemeAjax.messages.installFailed);
                alert(builderProThemeAjax.messages.genericError);
              }
            });
          });

          // Activate theme handler (use .off() to prevent multiple bindings)
          $('#activate-builderpro-theme').off('click').on('click', function(e) {
            e.preventDefault();
            var button = $(this);
            
            // Prevent multiple activations
            if (activateInProgress) {
              console.log('Activation already in progress, ignoring click');
              return;
            }
            
            activateInProgress = true;
            button.prop('disabled', true).text(builderProThemeAjax.messages.activating);
            
            $.ajax({
              url: builderProThemeAjax.ajaxurl,
              type: 'POST',
              timeout: 15000, // 15 second timeout
              data: {
                action: 'activate_builderpro_theme',
                nonce: builderProThemeAjax.activateNonce
              },
              success: function(response) {
                if (response.success) {
                  button.text(builderProThemeAjax.messages.activated);
                  setTimeout(function() {
                    location.reload();
                  }, 1000);
                } else {
                  activateInProgress = false;
                  button.prop('disabled', false).text(builderProThemeAjax.messages.activateFailed);
                  alert(builderProThemeAjax.messages.activateError + (response.data || 'Unknown error'));
                }
              },
              error: function(xhr, status, error) {
                activateInProgress = false;
                console.log('AJAX Error:', xhr.responseText);
                button.prop('disabled', false).text(builderProThemeAjax.messages.activateFailed);
                alert(builderProThemeAjax.messages.genericError);
              }
            });
          });

          // Cleanup orphaned themes handler (use .off() to prevent multiple bindings)
          $('#cleanup-orphaned-themes').off('click').on('click', function(e) {
            e.preventDefault();
            var button = $(this);
            
            // Prevent multiple cleanups
            if (cleanupInProgress) {
              console.log('Cleanup already in progress, ignoring click');
              return;
            }
            
            if (!confirm('This will clean up theme references that no longer exist in your filesystem. Continue?')) {
              return;
            }
            
            cleanupInProgress = true;
            button.prop('disabled', true).text(builderProThemeAjax.messages.cleaning);
            
            $.ajax({
              url: builderProThemeAjax.ajaxurl,
              type: 'POST',
              timeout: 20000, // 20 second timeout
              data: {
                action: 'cleanup_orphaned_themes',
                nonce: builderProThemeAjax.cleanupNonce
              },
              success: function(response) {
                if (response.success) {
                  button.text(builderProThemeAjax.messages.cleaned);
                  
                  var message = 'Cleanup complete!\n\n';
                  if (response.data) {
                    var data = response.data;
                    message += 'Themes before: ' + data.themes_before + '\n';
                    message += 'Themes after: ' + data.themes_after + '\n';
                    
                    if (data.duplicates_removed > 0) {
                      message += 'Duplicate BuilderPro themes removed: ' + data.duplicates_removed + '\n';
                    }
                    
                    if (data.orphaned_removed > 0) {
                      message += 'Orphaned theme references removed: ' + data.orphaned_removed + '\n';
                    }
                    
                    if (data.duplicates_removed === 0 && data.orphaned_removed === 0) {
                      message += 'No issues found - themes are already clean!\n';
                    }
                    
                    if (data.actions_taken && data.actions_taken.length > 0) {
                      message += '\nActions taken:\n' + data.actions_taken.join('\n');
                    }
                  }
                  
                  alert(message);
                  setTimeout(function() {
                    location.reload();
                  }, 1500);
                } else {
                  cleanupInProgress = false;
                  button.prop('disabled', false).text(builderProThemeAjax.messages.cleanupFailed);
                  alert(builderProThemeAjax.messages.cleanupError + (response.data || 'Unknown error'));
                }
              },
              error: function(xhr, status, error) {
                cleanupInProgress = false;
                console.log('Cleanup AJAX Error:', xhr.responseText);
                button.prop('disabled', false).text(builderProThemeAjax.messages.cleanupFailed);
                alert(builderProThemeAjax.messages.genericError);
              }
            });
          });
        });
        </script>
        <?php
    }

    /**
     * Handle AJAX request to install BuilderPro Base Theme
     */
    public function handleInstallBuilderProTheme(): void
    {
        // Check if nonce exists
        if (!isset($_POST['nonce'])) {
            wp_send_json_error('No security token provided.');
            return;
        }

        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'install_builderpro_theme')) {
            wp_send_json_error('Security check failed.');
            return;
        }

        // Check user permissions
        if (!UserRoles::isContextAdministrator()) {
            wp_send_json_error('Insufficient permissions.');
            return;
        }

        // Get the remove other themes option
        $removeOtherThemes = isset($_POST['remove_other_themes']) && $_POST['remove_other_themes'] === '1';

        try {
            // Install the BuilderPro Base Theme
            ThemesService::installBuilderProBaseTheme();

            // If option is checked, remove all other themes
            if ($removeOtherThemes) {
                ThemesService::deletePreviousThemes();
            }

            $message = 'BuilderPro Base Theme installed successfully.';
            if ($removeOtherThemes) {
                $message .= ' All other themes have been removed.';
            }

            wp_send_json_success($message);
        } catch (\Exception $e) {
            wp_send_json_error('Installation failed: ' . $e->getMessage());
        } catch (\Error $e) {
            wp_send_json_error('Installation failed (Fatal Error): ' . $e->getMessage());
        }
    }

    /**
     * Handle AJAX request to activate BuilderPro Base Theme
     */
    public function handleActivateBuilderProTheme(): void
    {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'activate_builderpro_theme')) {
            wp_send_json_error('Security check failed.');
            return;
        }

        // Check user permissions
        if (!UserRoles::isContextAdministrator()) {
            wp_send_json_error('Insufficient permissions.');
            return;
        }

        try {
            ThemesService::activateBuilderProBaseTheme();
            wp_send_json_success('BuilderPro Base Theme activated successfully.');
        } catch (\Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }

    /**
     * Handle AJAX request to cleanup orphaned themes
     */
    public function handleCleanupOrphanedThemes(): void
    {
        // Check if nonce exists
        if (!isset($_POST['nonce'])) {
            wp_send_json_error('No security token provided.');
            return;
        }

        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'cleanup_orphaned_themes')) {
            wp_send_json_error('Security check failed.');
            return;
        }

        // Check user permissions
        if (!UserRoles::isContextAdministrator()) {
            wp_send_json_error('Insufficient permissions.');
            return;
        }

        try {
            $cleanup_result = ThemesService::cleanupOrphanedThemes();
            wp_send_json_success($cleanup_result);
        } catch (\Exception $e) {
            wp_send_json_error('Cleanup failed: ' . $e->getMessage());
        } catch (\Error $e) {
            wp_send_json_error('Cleanup failed (Fatal Error): ' . $e->getMessage());
        }
    }
}
