<?php

declare( strict_types=1 );

namespace StrykeWP\Admin;

use StrykeWP\Core\AssetManager;
use StrykeWP\Core\Logger;
use StrykeWP\Core\Migrator;
use StrykeWP\Core\OptionManager;
use StrykeWP\Modules\ModuleInterface;
use StrykeWP\Modules\ModuleRegistry;

/**
 * STRYKE WP Admin Dashboard renderer.
 *
 * Outputs the full custom admin UI: sidebar navigation + main content area.
 * CSS overrides hide WordPress's default admin chrome on these pages so the
 * STRYKE dark theme takes complete control of the screen.
 *
 * @package StrykeWP\Admin
 */
class Dashboard {

	public function __construct(
		private readonly ModuleRegistry $registry,
		private readonly AssetManager   $assets,
		private readonly OptionManager  $options,
		private readonly Logger         $logger,
	) {}

	// ---------------------------------------------------------------------------
	// Hook Registration
	// ---------------------------------------------------------------------------

	public function register_hooks(): void {
		add_action( 'wp_ajax_stryke_wp_toggle_module', [ $this, 'ajax_toggle_module' ] );
	}

	// ---------------------------------------------------------------------------
	// Page Renderers
	// ---------------------------------------------------------------------------

	/**
	 * Renders the main overview dashboard page.
	 */
	public function render_overview(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Zugriff verweigert.', 'stryke-wp' ) );
		}

		$this->render_shell( 'overview', function (): void {
			$this->render_overview_content();
		} );
	}

	/**
	 * Renders a module-specific settings page.
	 * Dispatches to the correct module based on the `page` query param.
	 */
	public function render_module_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Zugriff verweigert.', 'stryke-wp' ) );
		}

		// Derive module ID from page slug: 'stryke-wp-connector' → 'connector'.
		$page      = sanitize_key( $_GET['page'] ?? '' );
		$module_id = str_replace( 'stryke-wp-', '', $page );
		$module    = $this->registry->get( $module_id );

		if ( null === $module ) {
			wp_die( esc_html__( 'Modul nicht gefunden.', 'stryke-wp' ) );
		}

		$this->render_shell( $module_id, function () use ( $module ): void {
			$this->render_module_content( $module );
		} );
	}

	// ---------------------------------------------------------------------------
	// Shell Layout
	// ---------------------------------------------------------------------------

	/**
	 * Renders the full-screen STRYKE WP layout shell (sidebar + main).
	 *
	 * When the Branding module is active it already provides a global shell
	 * (topbar + sidebar) on every admin page.  In that case we only render
	 * the inner content — no wrapper div, no duplicate sidebar.
	 *
	 * @param string   $active_id Active nav item identifier.
	 * @param callable $content   Callable that renders the main content area.
	 */
	private function render_shell( string $active_id, callable $content ): void {
		if ( $this->registry->is_enabled( 'branding' ) ) {
			// Branding module provides the outer shell; just render content.
			$content();
			return;
		}

		// Standalone mode — render our own shell.
		?>
		<div class="stryke-wp-wrap" id="stryke-wp-app">

			<?php $this->render_sidebar( $active_id ); ?>

			<main class="stryke-main" role="main">
				<div class="stryke-main__inner">
					<?php $content(); ?>
				</div>
			</main>

		</div>
		<?php
	}

	/**
	 * Renders the left navigation sidebar.
	 *
	 * @param string $active_id Currently active page identifier.
	 */
	private function render_sidebar( string $active_id ): void {
		?>
		<aside class="stryke-sidebar" aria-label="<?php esc_attr_e( 'STRYKE Navigation', 'stryke-wp' ); ?>">

			<!-- Logo -->
			<div class="stryke-sidebar__logo">
				<?php
				$logo_path = STRYKE_WP_DIR . '/src/Modules/Branding/assets/img/stryke-logo.png';
				if ( file_exists( $logo_path ) ) :
					$logo_url = plugins_url( 'src/Modules/Branding/assets/img/stryke-logo.png', STRYKE_WP_DIR . '/stryke-wp.php' );
				?>
					<img src="<?php echo esc_url( $logo_url ); ?>" alt="STRYKE WP" height="28" style="width:auto" />
				<?php else : ?>
					<span class="stryke-logo__mark">S</span>
					<span class="stryke-logo__text">STRYKE <strong>WP</strong></span>
				<?php endif; ?>
			</div>

			<!-- Navigation -->
			<nav class="stryke-nav" aria-label="<?php esc_attr_e( 'Hauptnavigation', 'stryke-wp' ); ?>">
				<ul>
					<li>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=stryke-wp' ) ); ?>"
						   class="stryke-nav__item <?php echo 'overview' === $active_id ? 'is-active' : ''; ?>">
							<span class="dashicons dashicons-dashboard" aria-hidden="true"></span>
							<?php esc_html_e( 'Dashboard', 'stryke-wp' ); ?>
						</a>
					</li>

					<?php foreach ( $this->registry->all() as $module ) : ?>
						<?php
						$is_active = $module->get_id() === $active_id;
						$is_on     = $this->registry->is_enabled( $module->get_id() );
						?>
						<li>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=stryke-wp-' . $module->get_id() ) ); ?>"
							   class="stryke-nav__item <?php echo $is_active ? 'is-active' : ''; ?>"
							   title="<?php echo esc_attr( $module->get_description() ); ?>">
								<span class="dashicons <?php echo esc_attr( $module->get_icon() ); ?>" aria-hidden="true"></span>
								<?php echo esc_html( $module->get_name() ); ?>
								<?php if ( $is_on ) : ?>
									<span class="stryke-badge stryke-badge--on" aria-label="<?php esc_attr_e( 'Aktiv', 'stryke-wp' ); ?>"></span>
								<?php endif; ?>
							</a>
						</li>
					<?php endforeach; ?>
				</ul>
			</nav>

			<!-- Sidebar footer -->
			<div class="stryke-sidebar__footer">
				<?php if ( $this->registry->is_enabled( 'branding' ) ) : ?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=stryke-wp-support' ) ); ?>"
					   class="stryke-footer-link <?php echo 'support' === $active_id ? 'stryke-footer-link--active' : ''; ?>">
						<span class="dashicons dashicons-sos" aria-hidden="true"></span>
						<?php esc_html_e( 'Support', 'stryke-wp' ); ?>
					</a>
				<?php endif; ?>
				<span class="stryke-version">STRYKE WP v<?php echo esc_html( STRYKE_WP_VERSION ); ?></span>
				<a href="https://www.strykemarketing.de/" target="_blank" rel="noopener noreferrer" class="stryke-footer-link">by STRYKE Marketing</a>
			</div>

		</aside>
		<?php
	}

	// ---------------------------------------------------------------------------
	// Content Areas
	// ---------------------------------------------------------------------------

	/**
	 * Renders the module overview grid (main dashboard page content).
	 */
	private function render_overview_content(): void {
		$enabled_count = 0;
		foreach ( $this->registry->all() as $id => $m ) {
			if ( $this->registry->is_enabled( $id ) ) {
				$enabled_count++;
			}
		}
		$total = count( $this->registry->all() );
		?>
		<header class="stryke-page-header">
			<h1 class="stryke-page-title">
				<?php esc_html_e( 'Dashboard', 'stryke-wp' ); ?>
			</h1>
			<p class="stryke-page-subtitle">
				<?php
				printf(
					/* translators: 1: enabled module count, 2: total module count */
					esc_html__( '%1$d von %2$d Modulen aktiv', 'stryke-wp' ),
					$enabled_count,
					$total
				);
				?>
			</p>
		</header>

		<?php $this->render_migration_notice(); ?>

		<div class="stryke-module-grid">
			<?php foreach ( $this->registry->all() as $module ) : ?>
				<?php $this->render_module_card( $module ); ?>
			<?php endforeach; ?>
		</div>
		<?php
	}

	/**
	 * Displays a one-time notice after a successful automatic migration from
	 * individual STRYKE plugins. Clears the transient after displaying.
	 *
	 * @return void
	 */
	private function render_migration_notice(): void {
		$migrated = get_transient( Migrator::TRANSIENT_MIGRATION_NOTICE );

		if ( ! is_array( $migrated ) || empty( $migrated ) ) {
			return;
		}

		delete_transient( Migrator::TRANSIENT_MIGRATION_NOTICE );

		// Map module IDs to human-readable module names.
		$names = [
			'connector' => __( 'Hub Connector', 'stryke-wp' ),
			'branding'  => __( 'Admin Branding', 'stryke-wp' ),
			'backup'    => __( 'Google Drive Backup', 'stryke-wp' ),
			'wip_mode'  => __( 'WIP Modus', 'stryke-wp' ),
		];

		$module_list = implode(
			', ',
			array_map(
				static fn( string $id ) => '<strong>' . esc_html( $names[ $id ] ?? $id ) . '</strong>',
				$migrated
			)
		);
		?>
		<div class="stryke-notice stryke-notice--success" style="margin-bottom: 24px;">
			<span class="dashicons dashicons-migrate" aria-hidden="true"></span>
			<div>
				<strong><?php esc_html_e( 'Migration erfolgreich', 'stryke-wp' ); ?></strong><br>
				<?php
				printf(
					/* translators: %s: comma-separated list of module names */
					wp_kses(
						__( 'Bestehende Daten aus deinen Einzel-Plugins wurden automatisch übernommen und folgende Module wurden aktiviert: %s. Du kannst die Einzel-Plugins jetzt deaktivieren.', 'stryke-wp' ),
						[ 'strong' => [] ]
					),
					$module_list // Already escaped above via esc_html() inside each item.
				);
				?>
			</div>
		</div>
		<?php
	}

	/**
	 * Renders a single module card in the overview grid.
	 *
	 * @param ModuleInterface $module The module to render.
	 */
	private function render_module_card( ModuleInterface $module ): void {
		$id         = $module->get_id();
		$is_enabled = $this->registry->is_enabled( $id );
		$slug       = 'stryke-wp-' . $id;
		$settings_url = admin_url( 'admin.php?page=' . $slug );
		?>
		<div class="stryke-card <?php echo $is_enabled ? 'stryke-card--active' : ''; ?>"
		     data-module="<?php echo esc_attr( $id ); ?>">

			<div class="stryke-card__header">
				<span class="stryke-card__icon dashicons <?php echo esc_attr( $module->get_icon() ); ?>" aria-hidden="true"></span>
				<div class="stryke-card__meta">
					<h2 class="stryke-card__name"><?php echo esc_html( $module->get_name() ); ?></h2>
					<span class="stryke-card__version">v<?php echo esc_html( $module->get_version() ); ?></span>
				</div>
			</div>

			<p class="stryke-card__description">
				<?php echo esc_html( $module->get_description() ); ?>
			</p>

			<div class="stryke-card__footer">
				<!-- Toggle -->
				<label class="stryke-toggle" title="<?php echo $is_enabled ? esc_attr__( 'Deaktivieren', 'stryke-wp' ) : esc_attr__( 'Aktivieren', 'stryke-wp' ); ?>">
					<input type="checkbox"
					       class="stryke-toggle__input"
					       data-module-id="<?php echo esc_attr( $id ); ?>"
					       <?php checked( $is_enabled ); ?>>
					<span class="stryke-toggle__slider" aria-hidden="true"></span>
					<span class="stryke-toggle__label">
						<?php echo $is_enabled ? esc_html__( 'Aktiv', 'stryke-wp' ) : esc_html__( 'Inaktiv', 'stryke-wp' ); ?>
					</span>
				</label>

				<!-- Settings link -->
				<a href="<?php echo esc_url( $settings_url ); ?>" class="stryke-btn stryke-btn--ghost stryke-btn--sm">
					<?php esc_html_e( 'Einstellungen', 'stryke-wp' ); ?>
					<span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
				</a>
			</div>
		</div>
		<?php
	}

	/**
	 * Renders a module's individual settings page.
	 *
	 * @param ModuleInterface $module Module to render settings for.
	 */
	private function render_module_content( ModuleInterface $module ): void {
		$id         = $module->get_id();
		$is_enabled = $this->registry->is_enabled( $id );
		?>
		<header class="stryke-page-header stryke-page-header--compact">
			<div class="stryke-page-header__inner">
				<span class="dashicons <?php echo esc_attr( $module->get_icon() ); ?> stryke-page-header__icon" aria-hidden="true"></span>
				<h1 class="stryke-page-title"><?php echo esc_html( $module->get_name() ); ?></h1>
			</div>
			<div class="stryke-page-header__actions">
				<span class="stryke-version-badge">v<?php echo esc_html( $module->get_version() ); ?></span>
				<label class="stryke-toggle stryke-toggle--lg">
					<input type="checkbox"
					       class="stryke-toggle__input"
					       data-module-id="<?php echo esc_attr( $id ); ?>"
					       <?php checked( $is_enabled ); ?>>
					<span class="stryke-toggle__slider" aria-hidden="true"></span>
					<span class="stryke-toggle__label">
						<?php echo $is_enabled ? esc_html__( 'Aktiv', 'stryke-wp' ) : esc_html__( 'Inaktiv', 'stryke-wp' ); ?>
					</span>
				</label>
			</div>
		</header>

		<?php if ( ! $is_enabled ) : ?>
			<div class="stryke-module-description stryke-card">
				<p><?php echo esc_html( $module->get_description() ); ?></p>
				<div class="stryke-notice stryke-notice--info">
					<span class="dashicons dashicons-info" aria-hidden="true"></span>
					<?php esc_html_e( 'Aktiviere dieses Modul, um die Einstellungen zu sehen.', 'stryke-wp' ); ?>
				</div>
			</div>
		<?php else : ?>
			<?php $module->render_settings(); ?>
		<?php endif; ?>
		<?php
	}

	// ---------------------------------------------------------------------------
	// AJAX Handlers
	// ---------------------------------------------------------------------------

	/**
	 * AJAX handler for toggling a module on or off.
	 *
	 * POST params:
	 *  - nonce     : wp_nonce for 'stryke_wp_admin'
	 *  - module_id : sanitized module identifier
	 *  - enabled   : '1' to enable, '0' to disable
	 *
	 * Response: JSON { success: true, module_id: string, enabled: bool }
	 */
	public function ajax_toggle_module(): void {
		// Security checks.
		if ( ! check_ajax_referer( 'stryke_wp_admin', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Sicherheitstoken ungültig.', 'stryke-wp' ) ], 403 );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Zugriff verweigert.', 'stryke-wp' ) ], 403 );
		}

		$module_id = sanitize_key( $_POST['module_id'] ?? '' );
		$enabled   = rest_sanitize_boolean( $_POST['enabled'] ?? false );

		if ( empty( $module_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Ungültige Modul-ID.', 'stryke-wp' ) ], 400 );
		}

		$success = $enabled
			? $this->registry->enable( $module_id )
			: $this->registry->disable( $module_id );

		if ( ! $success ) {
			wp_send_json_error( [ 'message' => __( 'Modul nicht gefunden.', 'stryke-wp' ) ], 404 );
		}

		$this->logger->info( 'Module toggled.', [
			'module_id' => $module_id,
			'enabled'   => $enabled,
			'user_id'   => get_current_user_id(),
		] );

		wp_send_json_success( [
			'module_id' => $module_id,
			'enabled'   => $enabled,
			'message'   => $enabled
				? __( 'Modul aktiviert.', 'stryke-wp' )
				: __( 'Modul deaktiviert.', 'stryke-wp' ),
		] );
	}
}
