<?php
/**
 * Column mapping component view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Components
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Components;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Services\ColumnMappingService;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

/**
 * Column Mapping Component View
 *
 * Displays the interface for mapping CSV columns to target fields.
 *
 * @since 1.0.0
 */
class ColumnMappingComponentView extends AbstractView implements ViewInterface {

	/**
	 * Views factory.
	 *
	 * @since 1.0.0
	 * @var ViewsFactory
	 */
	private ViewsFactory $views_factory;

	/**
	 * Column mapping service.
	 *
	 * @since 1.0.0
	 * @var ColumnMappingService
	 */
	private ColumnMappingService $column_mapping_service;

	/**
	 * Icon helper.
	 *
	 * @since 1.0.0
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param ViewsFactory         $views_factory
	 * @param ColumnMappingService $column_mapping_service
	 * @param IconHelper           $icon_helper
	 */
	public function __construct(
		ViewsFactory $views_factory,
		ColumnMappingService $column_mapping_service,
		IconHelper $icon_helper
	) {
		$this->views_factory          = $views_factory;
		$this->column_mapping_service = $column_mapping_service;
		$this->icon_helper            = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args {
	 *     @type array $headers CSV headers
	 *     @type array $sample_data Sample row data
	 *     @type array $auto_mappings Auto-detected mappings
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$args = wp_parse_args(
			$args,
			[
				'headers'       => [],
				'sample_data'   => [],
				'auto_mappings' => [],
			]
		);

		$headers         = $args['headers'];
		$sample_data     = $args['sample_data'];
		$auto_mappings   = $args['auto_mappings'];
		$mapping_options = $this->column_mapping_service->get_mapping_options();

		if ( empty( $headers ) ) {
			return;
		}

		?>
		<div class="bg-white border border-gray-200 rounded-lg p-6">
			<div class="mb-4">
				<h3 class="text-lg font-medium text-gray-900 mb-2">
					<?php esc_html_e( 'Map CSV Columns to Fields', 'rewardswp' ); ?>
				</h3>
				<p class="text-sm text-gray-600">
					<?php esc_html_e( 'Select which field each CSV column should map to. Fields marked with * are required.', 'rewardswp' ); ?>
				</p>
			</div>

			<!-- Mapping Table -->
			<div class="overflow-hidden border border-gray-200 rounded-lg">
				<table class="min-w-full divide-y divide-gray-200">
					<thead class="bg-gray-50">
						<tr>
							<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								<?php esc_html_e( 'CSV Column', 'rewardswp' ); ?>
							</th>
							<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								<?php esc_html_e( 'Sample Data', 'rewardswp' ); ?>
							</th>
							<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								<?php esc_html_e( 'Map to Field', 'rewardswp' ); ?>
							</th>
							<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
								<?php esc_html_e( 'Status', 'rewardswp' ); ?>
							</th>
						</tr>
					</thead>
					<tbody class="bg-white divide-y divide-gray-200">
						<?php foreach ( $headers as $index => $header ) : ?>
							<?php
							$auto_mapping = $auto_mappings[ $header ] ?? [];
							$target_field = $auto_mapping['target_field'] ?? '';
							$confidence   = $auto_mapping['confidence'] ?? 0;
							$status       = $auto_mapping['status'] ?? 'unmapped';
							$sample_value = $sample_data[ $header ] ?? '';

							// Truncate long sample values.
							if ( strlen( $sample_value ) > 30 ) {
								$sample_value = substr( $sample_value, 0, 30 ) . '...';
							}
							?>
							<tr class="hover:bg-gray-50">
								<!-- CSV Column -->
								<td class="px-4 py-3 text-sm font-medium text-gray-900">
									<?php echo esc_html( $header ); ?>
								</td>

								<!-- Sample Data -->
								<td class="px-4 py-3 text-sm text-gray-500">
									<span class="font-mono text-xs bg-gray-100 px-2 py-1 rounded">
										<?php echo esc_html( $sample_value ); ?>
									</span>
								</td>

								<!-- Mapping Dropdown -->
								<td class="px-4 py-3">
									<?php
									$this->views_factory->get_view( SelectComponentView::class )->render(
										[
											'x-model'     => 'columnMappings[\'' . esc_attr( $header ) . '\']',
											'x-on:change' => 'validateMappings()',
											'options'     => $mapping_options,
											'selected'    => $target_field,
										]
									);
									?>
								</td>

								<!-- Status Indicator -->
								<td class="px-4 py-3">
									<div class="flex items-center">
										<?php if ( 'confident' === $status ) : ?>
											<div class="flex items-center text-green-600">
												<?php echo wp_kses( $this->icon_helper->get_icon( 'check-circle', 'w-4 h-4 mr-1' ), svg_kses() ); ?>
												<span class="text-xs font-medium"><?php esc_html_e( 'Confident', 'rewardswp' ); ?></span>
											</div>
										<?php elseif ( 'uncertain' === $status ) : ?>
											<div class="flex items-center text-yellow-600">
												<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-4 h-4 mr-1' ), svg_kses() ); ?>
												<span class="text-xs font-medium"><?php esc_html_e( 'Uncertain', 'rewardswp' ); ?></span>
											</div>
										<?php else : ?>
											<div class="flex items-center text-gray-400">
												<?php echo wp_kses( $this->icon_helper->get_icon( 'minus-circle', 'w-4 h-4 mr-1' ), svg_kses() ); ?>
												<span class="text-xs font-medium"><?php esc_html_e( 'Unmapped', 'rewardswp' ); ?></span>
											</div>
										<?php endif; ?>
									</div>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>

			<!-- Mapping Validation Messages -->
			<div x-show="mappingErrors.length > 0" class="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
				<div class="flex">
					<div class="flex-shrink-0">
						<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-5 h-5 text-red-400' ), svg_kses() ); ?>
					</div>
					<div class="ml-3">
						<h4 class="text-sm font-medium text-red-800">
							<?php esc_html_e( 'Mapping Issues', 'rewardswp' ); ?>
						</h4>
						<ul class="mt-1 text-sm text-red-700 list-disc list-inside">
							<template x-for="error in mappingErrors" x-key="error">
								<li x-text="error"></li>
							</template>
						</ul>
					</div>
				</div>
			</div>

			<!-- Mapping Success Message -->
			<div x-show="mappingErrors.length === 0 && Object.keys(columnMappings).length > 0" class="mt-4 p-3 bg-green-50 border border-green-200 rounded-md">
				<div class="flex">
					<div class="flex-shrink-0">
						<?php echo wp_kses( $this->icon_helper->get_icon( 'check-circle', 'w-5 h-5 text-green-400' ), svg_kses() ); ?>
					</div>
					<div class="ml-3">
						<p class="text-sm text-green-800">
							<?php esc_html_e( 'Mapping looks good! You can now preview your data.', 'rewardswp' ); ?>
						</p>
					</div>
				</div>
			</div>

			<!-- Mapping Summary -->
			<div x-show="Object.keys(columnMappings).length > 0" class="mt-4 p-4 bg-gray-50 rounded-md">
				<h4 class="text-sm font-medium text-gray-900 mb-2">
					<?php esc_html_e( 'Mapping Summary', 'rewardswp' ); ?>
				</h4>
				<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs text-gray-600">
					<div>
						<span class="font-medium text-gray-900"><?php esc_html_e( 'Mapped Columns:', 'rewardswp' ); ?></span>
						<span x-text="Object.values(columnMappings).filter(v => v && v !== 'skip').length"></span>
					</div>
					<div>
						<span class="font-medium text-gray-900"><?php esc_html_e( 'Skipped Columns:', 'rewardswp' ); ?></span>
						<span x-text="Object.values(columnMappings).filter(v => v === 'skip').length"></span>
					</div>
					<div>
						<span class="font-medium text-gray-900"><?php esc_html_e( 'Unmapped Columns:', 'rewardswp' ); ?></span>
						<span x-text="Object.values(columnMappings).filter(v => !v || v === '').length"></span>
					</div>
				</div>
			</div>

			<!-- Auto-Detection Info -->
			<?php if ( ! empty( $auto_mappings ) ) : ?>
				<div class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
					<div class="flex">
						<div class="flex-shrink-0">
							<?php echo wp_kses( $this->icon_helper->get_icon( 'lightbulb', 'w-5 h-5 text-blue-400' ), svg_kses() ); ?>
						</div>
						<div class="ml-3">
							<p class="text-sm text-blue-800">
								<?php
								$confident_count = count(
									array_filter(
										$auto_mappings,
										function ( $mapping ) {
											return ( $mapping['status'] ?? '' ) === 'confident';
										}
									)
								);

								if ( $confident_count > 0 ) {
									/* translators: %d: Number of column mappings automatically detected. */
									$mapping_phrase = _n(
										'We automatically detected %d column mapping with high confidence.',
										'We automatically detected %d column mappings with high confidence.',
										$confident_count,
										'rewardswp'
									);

									$message = sprintf( $mapping_phrase, $confident_count );

									printf( '%s', esc_html( $message ) );
								} else {
									esc_html_e( 'Please review and adjust the suggested mappings as needed.', 'rewardswp' );
								}
								?>
							</p>
						</div>
					</div>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}
}
