<?php
/**
 * Emails list content view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Parts
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Parts;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Services\EmailsService;
use function Awesomemotive\Rewardswp\Helpers\get_email_context_label;
use function Awesomemotive\Rewardswp\Helpers\get_email_contexts;
use function Awesomemotive\Rewardswp\Helpers\get_minimum_required_plan_for_feature;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_url;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\is_highest_plan_tier;
use function Awesomemotive\Rewardswp\Helpers\kses;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

/**
 * Class EmailsListContentView
 *
 * View for displaying emails grouped by context.
 *
 * @since 1.1.0
 */
class EmailsListContentView extends AbstractView implements ViewInterface {

	/**
	 * Emails service instance.
	 *
	 * @since 1.1.0
	 * @var EmailsService
	 */
	private EmailsService $emails_service;

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

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 * @param EmailsService $emails_service
	 * @param IconHelper    $icon_helper
	 */
	public function __construct(
		EmailsService $emails_service,
		IconHelper $icon_helper
	) {
		$this->emails_service = $emails_service;
		$this->icon_helper    = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     Optional arguments.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		// Get emails grouped by context with descriptions
		$grouped_emails     = $this->emails_service->get_emails_with_descriptions_grouped_by_context( false );
		$available_contexts = get_email_contexts();

		?>
		<div class="space-y-6">
			<?php foreach ( $available_contexts as $context ) : ?>
				<?php
				if ( ! isset( $grouped_emails[ $context ] ) || empty( $grouped_emails[ $context ] ) ) {
					continue;
				}
				?>

				<?php
				$context_label  = get_email_context_label( $context );
				$context_emails = $grouped_emails[ $context ];
				?>

				<?php
				/* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Contents are escaped by the function */
				echo wp_kses(
					get_view_component(
						'section',
						[
							'title'        => $context_label,
							'content'      => $this->get_emails_list_for_context( $context_emails, $context ),
							'id'           => 'emails_context_' . esc_attr( $context ),
							'default_open' => true,
						]
					),
					kses()
				);
				?>

			<?php endforeach; ?>

			<?php if ( empty( $grouped_emails ) ) : ?>
				<div class="text-center py-12">
					<div class="text-gray-400 text-6xl mb-4">📧</div>
					<h3 class="text-lg font-medium text-gray-900 mb-2">
						<?php esc_html_e( 'No emails found', 'rewardswp' ); ?>
					</h3>
					<p class="text-gray-500">
						<?php esc_html_e( 'Email templates will appear here once they are created.', 'rewardswp' ); ?>
					</p>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Get the emails list HTML for a specific context.
	 *
	 * @since 1.1.0
	 *
	 * @param array  $emails  Array of email data.
	 * @param string $context The context name.
	 *
	 * @return string The HTML content.
	 */
	private function get_emails_list_for_context( array $emails, string $context ): string {
		ob_start();
		?>

		<div class="grid gap-4">
			<?php foreach ( $emails as $email ) : ?>
				<?php
				$edit_url = add_query_arg(
					[
						'action'   => 'edit',
						'email_id' => $email['id'],
					],
					admin_url( 'admin.php?page=rewardswp-emails' )
				);

				$email_title        = ! empty( $email['display_title'] ) ? $email['display_title'] : ucwords( str_replace( '_', ' ', $email['name'] ) );
				$description        = ! empty( $email['description'] ) ? $email['description'] : $email_title;
			$is_enabled         = ! empty( $email['is_enabled'] );
			$has_access         = array_key_exists( 'has_access', $email ) ? (bool) $email['has_access'] : true;
			$is_pro_email       = ! empty( $email['is_pro_feature'] );
			$modal_feature_slug = $email['feature_slug'] ?? '';
				?>

			<div class="bg-white border border-gray-200 rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition-colors"
				x-on:click="setEmailForEdit(<?php echo esc_attr( $email['id'] ); ?>)">
					<div class="flex items-center justify-between gap-4">
						<div class="flex-1 min-w-0">
							<div class="flex items-center gap-3">
								<!-- Email specific icon -->
								<div class="flex-shrink-0">
									<?php echo wp_kses( $this->get_email_icon( $email['name'] ), svg_kses() ); ?>
								</div>
							<div class="flex-1 min-w-0">
								<h4 class="text-sm font-medium text-gray-900 truncate flex items-center gap-2">
									<?php echo esc_html( $email_title ); ?>
									<?php if ( $is_pro_email && ! $has_access ) : ?>
										<span class="ml-1">
											<?php
											// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped within the component
											echo get_view_component( 'badge', [ 'style' => 'pro' ] );
											?>
										</span>
									<?php endif; ?>
								</h4>
								<p class="text-sm text-gray-500 mt-1">
									<?php echo esc_html( $description ); ?>
								</p>
							</div>
							</div>
						</div>

						<div class="flex items-center gap-3 ml-auto flex-shrink-0">
						<!-- Edit/View button -->
						<button
							type="button"
							x-on:click="$event.stopPropagation(); setEmailForEdit(<?php echo esc_attr( $email['id'] ); ?>)"
							class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 cursor-pointer"
						>
							<?php echo esc_html( $has_access ? __( 'Edit', 'rewardswp' ) : __( 'Preview', 'rewardswp' ) ); ?>
						</button>

							<!-- Toggle Component -->
							<?php if ( $has_access ) : ?>
								<?php
								// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped within the component
								echo get_view_component(
									'toggle',
									[
										'section'      => '',
										'name'         => '',
										'is_checked'   => $is_enabled,
										'x_model'      => 'emailStatuses[' . esc_js( $email['id'] ) . ']',
										'x-on:click'   => '$event.stopPropagation()',
										'no_input'     => true,
										'button_align' => 'left',
									]
								);
								?>
							<?php else : ?>
								<?php
								// Build tooltip text with required plan.
								$min_plan     = ! empty( $modal_feature_slug ) ? get_minimum_required_plan_for_feature( $modal_feature_slug ) : 'Pro';
								$is_highest   = is_highest_plan_tier( $min_plan );
								$tooltip_text = sprintf(
									/* translators: %s: Plan name with optional + suffix */
									__( 'Requires %s', 'rewardswp' ),
									$min_plan . ( $is_highest ? '' : '+' )
								);
								?>
								<span data-tippy-content="<?php echo esc_attr( $tooltip_text ); ?>">
									<?php
									// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped within the component
									echo get_view_component(
										'toggle',
										[
											'section'             => '',
											'name'                => '',
											'is_checked'          => false,
											'x_model'             => '',
											'no_input'            => true,
											'locked'              => true,
											'button_align'        => 'left',
										]
									);
									?>
								</span>
							<?php endif; ?>
						</div>
					</div>
				</div>

			<?php endforeach; ?>
		</div>

		<?php
		return ob_get_clean();
	}

	/**
	 * Get the appropriate SVG icon for a specific email.
	 *
	 * @since 1.1.0
	 *
	 * @param string $email_name The email name/identifier.
	 *
	 * @return string The SVG icon markup.
	 */
	private function get_email_icon( string $email_name ): string {
		$icon_map = [
			// Account emails
			'welcome_member_points'   => 'reward-points',      // Welcome points for new members

			// Referral emails
			'advocate_reward_email'   => 'confetti',           // Advocate gets reward
			'friend_reward_email'     => 'confetti',           // Friend gets reward

			// Points emails
			'birthday_reward'         => 'earn-birthday',      // Birthday reward points
			'points_earned'           => 'reward-points',      // General points earned
			'points_expiration_email' => 'clock-alert',        // Points expiration warning

			// Order/Redemption emails
			'reward_redemption'       => 'reward-redemption',  // Reward redemption confirmation
		];

		$icon_name = $icon_map[ $email_name ] ?? 'envelope';

		return $this->icon_helper->get_icon( $icon_name, 'size-8 text-gray-700' );
	}
}