<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Admin;

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

use Signocore\Multilanguage\Application\Constants;
use Signocore\Multilanguage\Application\Entitlements;
use Signocore\Multilanguage\Application\LicenseManager;
use Signocore\Multilanguage\Features\LanguageManager;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;
use Signocore\Multilanguage\Support\FlagHelper;
use Signocore\Multilanguage\Support\PostTypeHelper;
use Signocore\Multilanguage\Support\TaxonomyHelper;

final class Dashboard
{
	use Singleton;

	private const BRAND_COLOR = '#b8642a';

	protected function init(): void
	{
		add_action('admin_init', [$this, 'handleRerunWizard']);
	}

	/**
	 * Handle re-running the setup wizard.
	 */
	public function handleRerunWizard(): void
	{
		if (!isset($_GET['sml_action']) || $_GET['sml_action'] !== 'rerun_wizard') {
			return;
		}

		if (!current_user_can('manage_options')) {
			return;
		}

		if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'sml_rerun_wizard')) {
			return;
		}

		delete_option(Constants::OPTION_PREFIX . 'wizard_completed');
		wp_safe_redirect(admin_url('admin.php?page=sml-setup-wizard'));
		exit;
	}

	public function renderDashboard(): void
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		$manager = LanguageManager::load();
		$activeLanguages = $manager->getActiveLanguages();
		$defaultLanguage = $manager->getDefaultLanguage();
		$stats = $this->getTranslationStats($activeLanguages);

		?>
		<div class="wrap">
			<h1 class="sml-page-title">
				<?php echo esc_html__('Signocore Multilanguage', 'signocore-multilanguage'); ?>
				<span class="sml-version"><?php echo esc_html('v' . Constants::$pluginVersion); ?></span>
			</h1>

			<?php $this->renderSetupNotice($activeLanguages); ?>

			<?php if (count($activeLanguages) > 1) : ?>
				<?php $this->renderStatCards($stats, $activeLanguages); ?>
			<?php endif; ?>

			<div id="poststuff">
				<div id="post-body" class="metabox-holder columns-2">
					<div id="post-body-content">
						<?php $this->renderLanguageOverview($activeLanguages, $defaultLanguage); ?>
						<?php $this->renderTranslationStats($stats, $activeLanguages); ?>
					</div>

					<div id="postbox-container-1" class="postbox-container">
						<?php $this->renderQuickLinks(); ?>
						<?php $this->renderPlanInfo(); ?>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Show a notice when only one language is configured.
	 *
	 * @param array<string, object> $activeLanguages
	 */
	private function renderSetupNotice(array $activeLanguages): void
	{
		if (count($activeLanguages) > 1) {
			return;
		}

		?>
		<div class="notice notice-warning">
			<p>
				<?php
				printf(
					/* translators: %s: link to languages page */
					esc_html__('You only have one language configured. %s to start translating your content.', 'signocore-multilanguage'),
					'<a href="' . esc_url(admin_url('admin.php?page=signocore-ml-languages')) . '">'
						. esc_html__('Add at least one more language', 'signocore-multilanguage')
						. '</a>'
				);
				?>
			</p>
			<p>
				<?php
				printf(
					/* translators: %s: link to re-run wizard */
					esc_html__('Or %s to configure languages, URL strategy, and more.', 'signocore-multilanguage'),
					'<a href="' . esc_url(wp_nonce_url(
						admin_url('admin.php?page=signocore-ml-dashboard&sml_action=rerun_wizard'),
						'sml_rerun_wizard'
					)) . '">'
						. esc_html__('re-run the setup wizard', 'signocore-multilanguage')
						. '</a>'
				);
				?>
			</p>
		</div>
		<?php
	}

	/**
	 * Render the stat cards grid above the main content.
	 *
	 * @param array{total_posts: int, total_terms: int, total_content: int, translated_count: int, translated_percent: float, per_language: array<string, int>, per_type: array<string, array{label: string, total: int, translated: int}>} $stats
	 * @param array<string, object> $activeLanguages
	 */
	private function renderStatCards(array $stats, array $activeLanguages): void
	{
		$nonDefaultCount = max(1, count($activeLanguages) - 1);
		?>
		<div class="sml-dashboard-stats">
			<div class="sml-stat-card">
				<div class="sml-stat-value"><?php echo esc_html((string) count($activeLanguages)); ?></div>
				<div class="sml-stat-label"><?php echo esc_html__('Active Languages', 'signocore-multilanguage'); ?></div>
			</div>
			<div class="sml-stat-card">
				<div class="sml-stat-value"><?php echo esc_html((string) $stats['total_content']); ?></div>
				<div class="sml-stat-label"><?php echo esc_html__('Total Content', 'signocore-multilanguage'); ?></div>
			</div>
			<div class="sml-stat-card sml-stat-brand">
				<div class="sml-stat-value"><?php echo esc_html((string) $stats['translated_count']); ?></div>
				<div class="sml-stat-label"><?php echo esc_html__('Translations', 'signocore-multilanguage'); ?></div>
			</div>
			<div class="sml-stat-card">
				<div class="sml-stat-value"><?php echo esc_html(number_format($stats['translated_percent'], 0)); ?>%</div>
				<div class="sml-stat-label"><?php echo esc_html__('Overall Progress', 'signocore-multilanguage'); ?></div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the language overview postbox.
	 *
	 * @param array<string, object> $activeLanguages
	 */
	private function renderLanguageOverview(array $activeLanguages, ?object $defaultLanguage): void
	{
		?>
		<div class="sml-card">
			<div class="sml-card-header">
				<h2><?php echo esc_html__('Language Overview', 'signocore-multilanguage'); ?></h2>
			</div>
			<div class="sml-card-body">
				<?php if (!empty($activeLanguages)) : ?>
					<ul style="margin: 0; padding: 0; list-style: none; display: flex; flex-wrap: wrap; gap: 8px;">
						<?php foreach ($activeLanguages as $lang) : ?>
							<li style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; background: var(--sml-gray-50); border: 1px solid var(--sml-border); border-radius: 20px; font-size: 13px;">
								<?php echo FlagHelper::getFlagImg($lang->code, 20, 15, $lang->name); ?>
								<span><?php echo esc_html($lang->name); ?></span>
								<code style="font-size: 11px; color: var(--sml-gray-500);"><?php echo esc_html($lang->code); ?></code>
								<?php if ((int) $lang->is_default) : ?>
									<span class="sml-default-badge" style="font-size: 9px; padding: 1px 6px;"><?php echo esc_html__('Default', 'signocore-multilanguage'); ?></span>
								<?php endif; ?>
							</li>
						<?php endforeach; ?>
					</ul>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the translation statistics postbox.
	 *
	 * @param array{total_posts: int, total_terms: int, total_content: int, translated_count: int, translated_percent: float, per_language: array<string, int>, per_type: array<string, array{label: string, total: int, translated: int}>} $stats
	 * @param array<string, object> $activeLanguages
	 */
	private function renderTranslationStats(array $stats, array $activeLanguages): void
	{
		?>
		<div class="sml-card">
			<div class="sml-card-header">
				<h2><?php echo esc_html__('Translation Statistics', 'signocore-multilanguage'); ?></h2>
			</div>
			<div class="sml-card-body">
				<?php if (!empty($stats['per_type'])) : ?>
					<table class="wp-list-table widefat fixed striped" style="border: 1px solid var(--sml-border); border-radius: var(--sml-radius);">
						<thead>
							<tr>
								<th><?php echo esc_html__('Content Type', 'signocore-multilanguage'); ?></th>
								<th style="width: 100px;"><?php echo esc_html__('Total', 'signocore-multilanguage'); ?></th>
								<th style="width: 100px;"><?php echo esc_html__('Translated', 'signocore-multilanguage'); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($stats['per_type'] as $typeData) : ?>
								<tr>
									<td><?php echo esc_html($typeData['label']); ?></td>
									<td><?php echo esc_html((string) $typeData['total']); ?></td>
									<td><?php echo esc_html((string) $typeData['translated']); ?></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				<?php endif; ?>

				<?php if (!empty($stats['per_language']) && count($activeLanguages) > 1) : ?>
					<h3 style="margin: 24px 0 12px; font-size: 0.875rem; font-weight: 600; color: var(--sml-gray-600);"><?php echo esc_html__('Per Language Progress', 'signocore-multilanguage'); ?></h3>
					<?php foreach ($activeLanguages as $lang) : ?>
						<?php
						if ((int) $lang->is_default) {
							continue;
						}
						$langCount = $stats['per_language'][$lang->code] ?? 0;
						$langPercent = $stats['total_content'] > 0
							? ($langCount / $stats['total_content']) * 100
							: 0;
						?>
						<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
							<div style="display: flex; align-items: center; gap: 6px; width: 140px; flex-shrink: 0;">
								<?php echo FlagHelper::getFlagImg($lang->code, 16, 12, $lang->name); ?>
								<span style="font-size: 13px; font-weight: 500;"><?php echo esc_html($lang->name); ?></span>
							</div>
							<div style="flex: 1;">
								<div class="sml-progress-bar">
									<div class="sml-progress-bar-fill" style="width: <?php echo esc_attr(number_format(min($langPercent, 100), 1)); ?>%;"></div>
								</div>
							</div>
							<span style="font-size: 12px; color: var(--sml-gray-500); width: 70px; text-align: right; flex-shrink: 0;">
								<?php echo esc_html((string) $langCount); ?> (<?php echo esc_html(number_format($langPercent, 0)); ?>%)
							</span>
						</div>
					<?php endforeach; ?>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the quick links postbox.
	 */
	private function renderQuickLinks(): void
	{
		?>
		<div class="sml-card">
			<div class="sml-card-header">
				<h3><?php echo esc_html__('Quick Links', 'signocore-multilanguage'); ?></h3>
			</div>
			<div class="sml-card-body">
				<ul style="margin: 0; padding: 0; list-style: none;">
					<li style="margin-bottom: 10px;">
						<a href="<?php echo esc_url(admin_url('admin.php?page=signocore-ml-languages')); ?>" style="display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--sml-primary); font-weight: 500;">
							<span class="dashicons dashicons-translation" style="font-size: 18px; width: 18px; height: 18px;"></span>
							<?php echo esc_html__('Languages', 'signocore-multilanguage'); ?>
						</a>
					</li>
					<li style="margin-bottom: 10px;">
						<a href="<?php echo esc_url(admin_url('admin.php?page=signocore-ml-settings')); ?>" style="display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--sml-primary); font-weight: 500;">
							<span class="dashicons dashicons-admin-generic" style="font-size: 18px; width: 18px; height: 18px;"></span>
							<?php echo esc_html__('Settings', 'signocore-multilanguage'); ?>
						</a>
					</li>
					<li style="margin-bottom: 10px;">
						<a href="<?php echo esc_url(admin_url('admin.php?page=signocore-ml-strings')); ?>" style="display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--sml-primary); font-weight: 500;">
							<span class="dashicons dashicons-editor-textcolor" style="font-size: 18px; width: 18px; height: 18px;"></span>
							<?php echo esc_html__('String Translation', 'signocore-multilanguage'); ?>
						</a>
					</li>
					<li>
						<a href="<?php echo esc_url(wp_nonce_url(
							admin_url('admin.php?page=signocore-ml-dashboard&sml_action=rerun_wizard'),
							'sml_rerun_wizard'
						)); ?>" style="display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--sml-primary); font-weight: 500;">
							<span class="dashicons dashicons-update" style="font-size: 18px; width: 18px; height: 18px;"></span>
							<?php echo esc_html__('Re-run setup wizard', 'signocore-multilanguage'); ?>
						</a>
					</li>
				</ul>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the plan info postbox.
	 */
	private function renderPlanInfo(): void
	{
		$license = LicenseManager::load();

		$freeFeatures = [
			sprintf(
				/* translators: %d: maximum number of languages on the free plan */
				__('Up to %d languages', 'signocore-multilanguage'),
				Entitlements::FREE_LANGUAGE_LIMIT
			),
			__('Post, page & CPT translation', 'signocore-multilanguage'),
			__('Taxonomy translation', 'signocore-multilanguage'),
			__('Media translation', 'signocore-multilanguage'),
			__('Content duplicator', 'signocore-multilanguage'),
			__('Language switcher (all styles)', 'signocore-multilanguage'),
			__('String translation', 'signocore-multilanguage'),
			__('Directory URLs', 'signocore-multilanguage'),
			__('Hreflang tags', 'signocore-multilanguage'),
		];

		$proFeatures = [];
		foreach (Entitlements::PRO_FEATURES as $feature) {
			$proFeatures[] = Entitlements::label($feature);
		}
		$proFeatures[] = __('Priority support', 'signocore-multilanguage');

		?>
		<div class="sml-card">
			<div class="sml-card-header">
				<h3><?php echo esc_html__('Your Plan', 'signocore-multilanguage'); ?></h3>
			</div>
			<div class="sml-card-body">
				<?php if ($license->isPro()) : ?>
					<p style="margin-top: 0; display: flex; align-items: center; gap: 6px;">
						<span class="dashicons dashicons-yes-alt" style="color: var(--sml-success);"></span>
						<strong><?php echo esc_html__('Pro', 'signocore-multilanguage'); ?></strong>
						&mdash; <?php echo esc_html__('All features unlocked.', 'signocore-multilanguage'); ?>
					</p>
				<?php else : ?>
					<p style="margin: 0 0 12px; display: flex; align-items: center; gap: 6px;">
						<span class="dashicons dashicons-yes-alt" style="color: var(--sml-success);"></span>
						<strong><?php echo esc_html__('Free', 'signocore-multilanguage'); ?></strong>
					</p>
					<ul style="margin: 0 0 16px; padding: 0; list-style: none;">
						<?php foreach ($freeFeatures as $feature) : ?>
							<li style="padding: 2px 0; font-size: 12px; color: var(--sml-gray-600);">
								<span class="dashicons dashicons-yes" style="font-size: 14px; width: 14px; height: 14px; color: var(--sml-success); vertical-align: middle;"></span>
								<?php echo esc_html($feature); ?>
							</li>
						<?php endforeach; ?>
					</ul>

					<p style="margin: 0 0 6px; font-size: 11px; font-weight: 600; color: var(--sml-gray-400); text-transform: uppercase; letter-spacing: 0.5px;"><?php echo esc_html__('Upgrade to Pro', 'signocore-multilanguage'); ?></p>
					<ul style="margin: 0 0 16px; padding: 0; list-style: none;">
						<?php foreach ($proFeatures as $feature) : ?>
							<li style="padding: 2px 0; font-size: 12px; color: var(--sml-gray-400);">
								<span class="dashicons dashicons-lock" style="font-size: 12px; width: 12px; height: 12px; color: var(--sml-brand); vertical-align: middle;"></span>
								<?php echo esc_html($feature); ?>
							</li>
						<?php endforeach; ?>
					</ul>

					<a href="<?php echo esc_url(LicenseManager::getUpgradeUrl()); ?>"
					   target="_blank"
					   class="sml-button small">
						<?php echo esc_html__('Upgrade to Pro', 'signocore-multilanguage'); ?>
					</a>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Gather translation statistics from the sml_translations table.
	 *
	 * @param array<string, object> $activeLanguages
	 * @return array{total_posts: int, total_terms: int, total_content: int, translated_count: int, translated_percent: float, per_language: array<string, int>, per_type: array<string, array{label: string, total: int, translated: int}>}
	 */
	private function getTranslationStats(array $activeLanguages): array
	{
		global $wpdb;

		$translationsTable = $wpdb->prefix . Constants::TABLE_TRANSLATIONS;
		$defaultLang = LanguageManager::load()->getDefaultLanguageCode();
		$nonDefaultCount = max(1, count($activeLanguages) - 1);

		/** @var array<string, array{label: string, total: int, translated: int}> $perType */
		$perType = [];

		// Count posts per translatable post type
		$totalPosts = 0;
		$translatableTypes = PostTypeHelper::getTranslatablePostTypes();
		foreach ($translatableTypes as $postType) {
			$count = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = %s",
					$postType
				)
			);

			if ($count === 0) {
				continue;
			}

			$elementTypePattern = 'post_' . $postType;
			$translated = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM `{$translationsTable}` WHERE element_type = %s AND language_code != %s",
					$elementTypePattern,
					$defaultLang
				)
			);

			$label = PostTypeHelper::getPostTypeLabel($postType);
			$perType['post_' . $postType] = [
				'label' => $label,
				'total' => $count,
				'translated' => $translated,
			];
			$totalPosts += $count;
		}

		// Count terms per translatable taxonomy
		$totalTerms = 0;
		$translatableTaxonomies = TaxonomyHelper::getTranslatableTaxonomies();
		foreach ($translatableTaxonomies as $taxonomy) {
			$count = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM {$wpdb->term_taxonomy} WHERE taxonomy = %s",
					$taxonomy
				)
			);

			if ($count === 0) {
				continue;
			}

			$elementTypePattern = 'tax_' . $taxonomy;
			$translated = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM `{$translationsTable}` WHERE element_type = %s AND language_code != %s",
					$elementTypePattern,
					$defaultLang
				)
			);

			$label = TaxonomyHelper::getTaxonomyLabel($taxonomy);
			$perType['tax_' . $taxonomy] = [
				'label' => $label,
				'total' => $count,
				'translated' => $translated,
			];
			$totalTerms += $count;
		}

		$totalContent = $totalPosts + $totalTerms;

		// Count non-default-language translations (actual translations, not source records)
		$translatedCount = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM `{$translationsTable}` WHERE language_code != %s",
				$defaultLang
			)
		);

		// Per-language counts (excluding default)
		/** @var array<string, int> $perLanguage */
		$perLanguage = [];

		/** @var array<int, object{language_code: string, count: string}>|null $rows */
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT language_code, COUNT(*) as count FROM `{$translationsTable}` WHERE language_code != %s GROUP BY language_code",
				$defaultLang
			)
		);

		if (is_array($rows)) {
			foreach ($rows as $row) {
				$perLanguage[$row->language_code] = (int) $row->count;
			}
		}

		$translatedPercent = $totalContent > 0 ? ($translatedCount / ($totalContent * $nonDefaultCount)) * 100 : 0.0;

		return [
			'total_posts' => $totalPosts,
			'total_terms' => $totalTerms,
			'total_content' => $totalContent,
			'translated_count' => $translatedCount,
			'translated_percent' => $translatedPercent,
			'per_language' => $perLanguage,
			'per_type' => $perType,
		];
	}
}
