<?php
/**
 * Unified EmberPrice admin page and navigation shell.
 *
 * @package EmberPrice
 */

namespace EmberPrice\Admin;

use EmberPrice\Core\LicenseManager;

defined( 'ABSPATH' ) || exit;

/**
 * Registers one visible WooCommerce submenu and renders the import, history,
 * and settings views inside a shared shell.
 */
final class AdminPage {

	private const MENU_SLUG  = 'emberprice';
	private const APP_HANDLE = 'embp-app';

	/**
	 * Settings form renderer and save handler.
	 *
	 * @var SettingsPage
	 */
	private SettingsPage $settings_page;

	/**
	 * Hook suffix returned by add_submenu_page().
	 *
	 * @var string
	 */
	private string $hook_suffix = '';

	/**
	 * Constructor.
	 *
	 * @param SettingsPage $settings_page Settings form renderer and handler.
	 */
	public function __construct( SettingsPage $settings_page ) {
		$this->settings_page = $settings_page;
	}

	/**
	 * Wires the unified page into WordPress.
	 */
	public function register(): void {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		$this->settings_page->register();
	}

	/**
	 * Registers the only visible EmberPrice submenu item.
	 */
	public function add_menu_page(): void {
		$hook_suffix = add_submenu_page(
			'woocommerce',
			__( 'EmberPrice', 'emberprice' ),
			__( 'EmberPrice', 'emberprice' ),
			'manage_woocommerce',
			self::MENU_SLUG,
			array( $this, 'render' )
		);

		if ( is_string( $hook_suffix ) ) {
			$this->hook_suffix = $hook_suffix;
		}

		$legacy_history_hook = add_submenu_page(
			null,
			__( 'EmberPrice History', 'emberprice' ),
			__( 'EmberPrice History', 'emberprice' ),
			'manage_woocommerce',
			'emberprice-history',
			'__return_null'
		);

		if ( is_string( $legacy_history_hook ) ) {
			add_action( 'load-' . $legacy_history_hook, array( $this, 'redirect_legacy_history' ) );
		}

		$legacy_settings_hook = add_submenu_page(
			null,
			__( 'EmberPrice Settings', 'emberprice' ),
			__( 'EmberPrice Settings', 'emberprice' ),
			'manage_woocommerce',
			'emberprice-settings',
			'__return_null'
		);

		if ( is_string( $legacy_settings_hook ) ) {
			add_action( 'load-' . $legacy_settings_hook, array( $this, 'redirect_legacy_settings' ) );
		}
	}

	/**
	 * Redirects the former history page to its canonical internal view.
	 */
	public function redirect_legacy_history(): void {
		$this->redirect_legacy_view( 'history' );
	}

	/**
	 * Redirects the former settings page to its canonical internal view.
	 */
	public function redirect_legacy_settings(): void {
		$this->redirect_legacy_view( 'settings' );
	}

	/**
	 * Preserves supported notices while redirecting a legacy page.
	 *
	 * @param string $view Canonical target view.
	 */
	private function redirect_legacy_view( string $view ): void {
		$query_args = array(
			'page' => self::MENU_SLUG,
			'view' => $view,
		);

		foreach ( array( 'updated', 'license_error' ) as $notice_arg ) {
			if ( isset( $_GET[ $notice_arg ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				$query_args[ $notice_arg ] = sanitize_text_field( wp_unslash( $_GET[ $notice_arg ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			}
		}

		wp_safe_redirect( add_query_arg( $query_args, admin_url( 'admin.php' ) ) );
		exit;
	}

	/**
	 * Enqueues the shared stylesheet on every view and the React bundle only
	 * where a React application is mounted.
	 *
	 * @param string $hook_suffix Current admin screen hook suffix.
	 */
	public function enqueue_assets( string $hook_suffix ): void {
		if ( '' === $this->hook_suffix || $hook_suffix !== $this->hook_suffix ) {
			return;
		}

		$asset_file = EMBP_PLUGIN_DIR . 'build/index.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = require $asset_file;
		$view  = $this->current_view();

		wp_enqueue_style( 'wp-components' );

		if ( file_exists( EMBP_PLUGIN_DIR . 'build/style-index.css' ) ) {
			wp_enqueue_style(
				self::APP_HANDLE,
				EMBP_PLUGIN_URL . 'build/style-index.css',
				array( 'wp-components' ),
				$asset['version']
			);
			wp_style_add_data( self::APP_HANDLE, 'rtl', 'replace' );
		}

		if ( 'settings' === $view ) {
			return;
		}

		wp_enqueue_script(
			self::APP_HANDLE,
			EMBP_PLUGIN_URL . 'build/index.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		wp_set_script_translations( self::APP_HANDLE, 'emberprice' );

		$script_settings = array(
			'root'  => esc_url_raw( rest_url() ),
			'nonce' => wp_create_nonce( 'wp_rest' ),
		);

		if ( 'import' === $view ) {
			$script_settings['sampleFileUrl']  = esc_url_raw( EMBP_PLUGIN_URL . 'assets/sample-price-list.csv' );
			$script_settings['sampleFileName'] = 'sample-price-list.csv';
		}

		wp_localize_script( self::APP_HANDLE, 'embpSettings', $script_settings );
	}

	/**
	 * Renders the shared shell and selected view.
	 */
	public function render(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$view      = $this->current_view();
		$view_data = $this->view_data( $view );
		?>
		<div class="wrap embp-admin-shell">
			<header class="embp-admin-header">
				<div class="embp-admin-brand">
					<img
						class="embp-admin-brand__mark"
						src="<?php echo esc_url( EMBP_PLUGIN_URL . 'assets/emberprice-logo-mark.png' ); ?>"
						width="40"
						height="40"
						alt=""
						aria-hidden="true"
					>
					<div>
						<h1>EmberPrice</h1>
						<p><?php esc_html_e( 'Supplier price updates for WooCommerce.', 'emberprice' ); ?></p>
					</div>
				</div>

				<div class="embp-admin-header__actions">
					<?php if ( class_exists( '\\EmberPrice\\Llm\\LlmClientFactory' ) ) : ?>
						<span class="embp-plan-badge">
							<?php echo esc_html( LicenseManager::is_pro() ? __( 'Pro', 'emberprice' ) : __( 'Free', 'emberprice' ) ); ?>
						</span>
					<?php endif; ?>
					<?php if ( 'import' !== $view ) : ?>
						<a class="button button-primary" href="<?php echo esc_url( $this->view_url( 'import' ) ); ?>">
							<?php esc_html_e( 'New import', 'emberprice' ); ?>
						</a>
					<?php endif; ?>
				</div>
			</header>

			<nav class="embp-admin-nav" aria-label="<?php esc_attr_e( 'EmberPrice navigation', 'emberprice' ); ?>">
				<?php $this->render_nav_link( 'import', __( 'Import', 'emberprice' ), $view ); ?>
				<?php $this->render_nav_link( 'history', __( 'History', 'emberprice' ), $view ); ?>
				<?php $this->render_nav_link( 'settings', __( 'Settings', 'emberprice' ), $view ); ?>
			</nav>

			<main class="embp-admin-content" aria-labelledby="embp-view-title">
				<div class="embp-view-heading">
					<h2 id="embp-view-title"><?php echo esc_html( $view_data['title'] ); ?></h2>
					<p><?php echo esc_html( $view_data['description'] ); ?></p>
				</div>

				<?php $this->render_view( $view ); ?>
			</main>
		</div>
		<?php
	}

	/**
	 * Returns the selected, allow-listed view.
	 */
	private function current_view(): string {
		// Read-only routing parameters do not require a nonce.
		$view = isset( $_GET['view'] ) ? sanitize_key( wp_unslash( $_GET['view'] ) ) : 'import'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		return in_array( $view, array( 'import', 'history', 'settings' ), true ) ? $view : 'import';
	}

	/**
	 * Builds a canonical view URL.
	 *
	 * @param string $view View identifier.
	 */
	private function view_url( string $view ): string {
		$query_args = array( 'page' => self::MENU_SLUG );

		if ( 'import' !== $view ) {
			$query_args['view'] = $view;
		}

		return add_query_arg( $query_args, admin_url( 'admin.php' ) );
	}

	/**
	 * Renders one navigation link.
	 *
	 * @param string $target_view Target view identifier.
	 * @param string $label       Link label.
	 * @param string $active_view Current view identifier.
	 */
	private function render_nav_link( string $target_view, string $label, string $active_view ): void {
		$class_name = 'embp-admin-nav__link';

		if ( $target_view === $active_view ) {
			$class_name .= ' is-active';
		}
		?>
		<a
			class="<?php echo esc_attr( $class_name ); ?>"
			href="<?php echo esc_url( $this->view_url( $target_view ) ); ?>"
			<?php
			if ( $target_view === $active_view ) :
				?>
				aria-current="page"<?php endif; ?>
		>
			<?php echo esc_html( $label ); ?>
		</a>
		<?php
	}

	/**
	 * Returns the heading copy for a view.
	 *
	 * @param string $view View identifier.
	 * @return array{title:string,description:string}
	 */
	private function view_data( string $view ): array {
		$data = array(
			'import'   => array(
				'title'       => __( 'Import a price list', 'emberprice' ),
				'description' => __( 'Upload a supplier file, review every change, and update WooCommerce safely.', 'emberprice' ),
			),
			'history'  => array(
				'title'       => __( 'Import history', 'emberprice' ),
				'description' => __( 'Resume unfinished imports, inspect results, or restore prices from a snapshot.', 'emberprice' ),
			),
			'settings' => array(
				'title'       => __( 'Settings', 'emberprice' ),
				'description' => __( 'Configure EmberPrice and control what happens to its data on uninstall.', 'emberprice' ),
			),
		);

		return $data[ $view ];
	}

	/**
	 * Renders the selected view content.
	 *
	 * @param string $view View identifier.
	 */
	private function render_view( string $view ): void {
		if ( 'history' === $view ) {
			echo '<div id="emberprice-history-app"></div>';
			return;
		}

		if ( 'settings' === $view ) {
			$this->settings_page->render();
			return;
		}

		echo '<div id="emberprice-app"></div>';
	}
}
