<?php

/**
 * Read-only code viewer metabox on built-block edit screens.
 *
 * @package LolaCore\BlockBuilder\Admin
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\BlockBuilder\Admin;

use LolaCore\BlockBuilder\Artifact\BlockArtifactAdapter;
use LolaCore\BlockBuilder\PostType\BlockPostType;
use LolaCore\PluginBuilder\Admin\ReviewQualityLabels;

if (! defined('ABSPATH')) {
	exit;
}

/**
 * Registers the Generated files metabox (block.json / JS / CSS tabs).
 */
class BlockEditScreen {

	private BlockArtifactAdapter $adapter;

	public function __construct( ?BlockArtifactAdapter $adapter = null ) {
		$this->adapter = $adapter ?? new BlockArtifactAdapter();
	}

	public function register(): void {
		add_action('add_meta_boxes', array($this, 'registerMetaBoxes'));
	}

	/**
	 * @param string $post_type Current post type.
	 */
	public function registerMetaBoxes( string $post_type ): void {
		if ($post_type !== BlockPostType::POST_TYPE) {
			return;
		}

		add_meta_box(
			'lolacore_bb_generated_files',
			__('Generated files', 'lolacore'),
			array($this, 'renderMetaBox'),
			BlockPostType::POST_TYPE,
			'normal',
			'high'
		);
	}

	/**
	 * @param \WP_Post $post Current post.
	 */
	public function renderMetaBox( \WP_Post $post ): void {
		$post_id = (int) $post->ID;

		$block_name  = (string) get_post_meta($post_id, BlockPostType::META_NAME, true);
		$plugin_slug = (string) get_post_meta($post_id, BlockPostType::META_PLUGIN_SLUG, true);
		$version     = max(1, (int) get_post_meta($post_id, BlockPostType::META_VERSION, true));
		$confidence  = (int) get_post_meta($post_id, BlockPostType::META_CONFIDENCE, true);
		$load_status = (string) get_post_meta($post_id, BlockPostType::META_LOAD_SAFE_STATUS, true);
		$note        = (string) get_post_meta($post_id, BlockPostType::META_CONFIDENCE_NOTE, true);
		$description = (string) get_post_meta($post_id, BlockPostType::META_DESCRIPTION, true);

		$files       = array();
		$incomplete  = true;
		try {
			$files      = $this->adapter->readBlockFilesMeta($post_id);
			$incomplete = $files === array();
		} catch (\Throwable $e) {
			$incomplete = true;
		}

		$block_json = (string) ( $files['block.json'] ?? '' );
		$edit_js    = (string) ( $files['edit.js'] ?? '' );
		$edit_asset = (string) ( $files['edit.asset.php'] ?? '' );
		$style_css  = (string) ( $files['style.css'] ?? '' );
		$render_php = (string) ( $files['render.php'] ?? '' );

		?>
		<div class="lolacore-pb-edit">
			<?php if ($incomplete) : ?>
				<p class="lolacore-pb-notice lolacore-pb-notice-warning">
					<?php esc_html_e('This block has incomplete generated files. Try updating it from chat or create a new version.', 'lolacore'); ?>
				</p>
			<?php endif; ?>

			<div class="lolacore-pb-meta-grid">
				<div class="lolacore-pb-meta-item">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Block name', 'lolacore'); ?></span>
					<code class="lolacore-pb-meta-value"><?php echo esc_html($block_name !== '' ? $block_name : '—'); ?></code>
				</div>
				<div class="lolacore-pb-meta-item">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Install folder', 'lolacore'); ?></span>
					<code class="lolacore-pb-meta-value"><?php echo esc_html($plugin_slug !== '' ? 'lolacore-blocks/' . $plugin_slug : '—'); ?></code>
				</div>
				<div class="lolacore-pb-meta-item">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Version', 'lolacore'); ?></span>
					<span class="lolacore-pb-meta-value"><?php echo esc_html((string) $version); ?></span>
				</div>
				<div class="lolacore-pb-meta-item lolacore-pb-meta-item-wide">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Status', 'lolacore'); ?></span>
					<span class="lolacore-pb-meta-value"><?php echo esc_html(LibraryColumns::installStatusLabel($post_id)); ?></span>
				</div>
				<?php
				$load_label = ReviewQualityLabels::loadTestLabel(array('status' => $load_status));
				if ($load_label !== '') :
					?>
				<div class="lolacore-pb-meta-item">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Load test', 'lolacore'); ?></span>
					<span class="lolacore-pb-meta-value"><?php echo esc_html($load_label); ?></span>
				</div>
				<?php endif; ?>
				<?php
				$review_label = ReviewQualityLabels::codeReviewLabel($confidence);
				if ($review_label !== '') :
					?>
				<div class="lolacore-pb-meta-item">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Code review', 'lolacore'); ?></span>
					<span class="lolacore-pb-meta-value"><?php echo esc_html($review_label); ?></span>
				</div>
				<?php endif; ?>
			</div>

			<?php if ($note !== '') : ?>
				<p class="lolacore-pb-confidence-note">
					<strong><?php esc_html_e('Review note', 'lolacore'); ?>:</strong>
					<?php echo esc_html($note); ?>
				</p>
			<?php endif; ?>

			<?php if ($description !== '') : ?>
				<div class="lolacore-pb-meta-item lolacore-pb-meta-item-wide">
					<span class="lolacore-pb-meta-label"><?php esc_html_e('Description', 'lolacore'); ?></span>
					<textarea class="lolacore-pb-readonly" rows="3" readonly><?php echo esc_textarea($description); ?></textarea>
				</div>
			<?php endif; ?>

			<div class="lolacore-pb-tabs" role="tablist" aria-label="<?php esc_attr_e('Generated source files', 'lolacore'); ?>">
				<button type="button" class="lolacore-pb-tab is-active" data-tab="json" role="tab" aria-selected="true">
					<?php esc_html_e('block.json', 'lolacore'); ?>
				</button>
				<button type="button" class="lolacore-pb-tab" data-tab="js" role="tab" aria-selected="false">
					<?php esc_html_e('edit.js', 'lolacore'); ?>
				</button>
				<button type="button" class="lolacore-pb-tab" data-tab="asset" role="tab" aria-selected="false">
					<?php esc_html_e('edit.asset.php', 'lolacore'); ?>
				</button>
				<button type="button" class="lolacore-pb-tab" data-tab="css" role="tab" aria-selected="false">
					<?php esc_html_e('style.css', 'lolacore'); ?>
				</button>
				<?php if ($render_php !== '') : ?>
				<button type="button" class="lolacore-pb-tab" data-tab="render" role="tab" aria-selected="false">
					<?php esc_html_e('render.php', 'lolacore'); ?>
				</button>
				<?php endif; ?>
			</div>

			<div class="lolacore-pb-tab-panels">
				<?php
				$this->renderCodePanel('json', $block_json, true);
				$this->renderCodePanel('js', $edit_js, false);
				$this->renderCodePanel('asset', $edit_asset, false);
				$this->renderCodePanel('css', $style_css, false);
				if ($render_php !== '') {
					$this->renderCodePanel('render', $render_php, false);
				}
				?>
			</div>
		</div>
		<?php
	}

	private function renderCodePanel( string $tab, string $code, bool $active ): void {
		$hidden = $active ? '' : ' hidden';
		$empty  = $code === '';
		?>
		<div class="lolacore-pb-tab-panel<?php echo esc_attr($hidden); ?>" data-panel="<?php echo esc_attr($tab); ?>" role="tabpanel">
			<?php if ($empty) : ?>
				<p class="lolacore-pb-notice"><?php esc_html_e('No file content stored for this tab.', 'lolacore'); ?></p>
			<?php else : ?>
				<textarea class="lolacore-pb-code" readonly spellcheck="false"><?php echo esc_textarea($code); ?></textarea>
			<?php endif; ?>
		</div>
		<?php
	}
}
