<?php
/**
 * Adjust points modal view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Modals
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Modals;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Controllers\Admin\MembersAdminController;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

/**
 * Adjust Points Modal View.
 *
 * @since 1.0.0
 */
class AdjustPointsModalView extends AbstractView implements ViewInterface {
	/**
	 * Icon helper for rendering icons.
	 *
	 * @since 1.0.0
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param IconHelper $icon_helper Icon helper instance.
	 */
	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args {
	 *     Required. An array of arguments.
	 *
	 *     @type int    $member_id      The member ID.
	 *     @type string $nonce          The member-specific nonce for security.
	 *     @type string $member_name    The member's display name.
	 *     @type int    $current_balance The member's current points balance.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$member_id       = isset( $args['member_id'] ) ? absint( $args['member_id'] ) : 0;
		$nonce           = isset( $args['nonce'] ) ? sanitize_text_field( $args['nonce'] ) : '';
		$member_name     = isset( $args['member_name'] ) ? sanitize_text_field( $args['member_name'] ) : '';
		$current_balance = isset( $args['current_balance'] ) ? absint( $args['current_balance'] ) : 0;

		$modal_data = [
			'errorMessageAmount'         => esc_html__( 'Please enter a valid points amount greater than zero.', 'rewardswp' ),
			'errorMessageReasonRequired' => esc_html__( 'Please provide a reason for deducting points.', 'rewardswp' ),
			'textAdd'                    => esc_html__( 'Add', 'rewardswp' ),
			'textDeduct'                 => esc_html__( 'Deduct', 'rewardswp' ),
			'textPoints'                 => esc_html__( 'Points', 'rewardswp' ),
			'successMessage'             => esc_html__( 'Points adjusted successfully.', 'rewardswp' ),
			'errorMessageGeneric'        => esc_html__( 'An unknown error occurred.', 'rewardswp' ),
			'errorMessageNetwork'        => esc_html__( 'A network error occurred. Please try again.', 'rewardswp' ),
			'nonce'                      => $nonce,
			'member_id'                  => $member_id,
			'member_name'                => $member_name,
			'current_balance'            => $current_balance,
			'large_deduction_threshold'  => 500, // Threshold for secondary confirmation.
		];

		?>
		<div
			x-data="adjustPointsModal(<?php echo esc_attr( wp_json_encode( $modal_data ) ); ?>)"
			x-show="showAdjustPointsModal"
			x-trap.inert.noscroll="showAdjustPointsModal"
			class="fixed inset-x-0 z-50 overflow-y-auto" style="top: var(--wp-admin--admin-bar--height, 32px); height: calc(100vh - var(--wp-admin--admin-bar--height, 32px))"
			aria-labelledby="modal-title"
			role="dialog"
			aria-modal="true"
			x-cloak
			x-on:keydown.escape.window="closeModal()"
						x-init="
				window.addEventListener('open-adjust-points-modal', function(e) {
					if (e.detail) {
						if (e.detail.memberId) member_id = e.detail.memberId;
						if (e.detail.memberName) member_name = e.detail.memberName;
						if (e.detail.currentBalance !== undefined) current_balance = e.detail.currentBalance;
					}
					showAdjustPointsModal = true;
					initializeMarker();
				});
			"
		>
			<div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
				<?php
				/*
				 * Background overlay
				 */
				?>
				<div
					x-show="showAdjustPointsModal"
					x-transition:enter="ease-out duration-300"
					x-transition:enter-start="opacity-0"
					x-transition:enter-end="opacity-100"
					x-transition:leave="ease-in duration-200"
					x-transition:leave-start="opacity-100"
					x-transition:leave-end="opacity-0"
					class="fixed inset-x-0 transition-opacity z-40" style="top: var(--wp-admin--admin-bar--height, 32px); height: calc(100vh - var(--wp-admin--admin-bar--height, 32px))"
					x-on:click="showConfirmationDialog ? (showConfirmationDialog = false) : closeModal()"
					aria-hidden="true"
				>
					<div class="absolute inset-0 bg-slate-900/40"></div>
				</div>

				<?php
				/*
				 * Modal panel
				 */
				?>
				<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
				<div
					x-show="showAdjustPointsModal"
					x-transition:enter="ease-out duration-300"
					x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
					x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
					x-transition:leave="ease-in duration-200"
					x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
					x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
					class="relative inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:w-full z-50"
					x-bind:class="showConfirmationDialog ? 'sm:max-w-lg' : 'sm:max-w-md'"
				>

					<?php
					/*
					 * Close button
					 */
					?>
					<button
						type="button"
						x-on:click="closeModal()"
						class="absolute top-2.5 right-2.5 cursor-pointer text-gray-400 hover:text-gray-500 z-10"
					>
						<?php echo wp_kses( $this->icon_helper->get_icon( 'modal-close', 'w-5 h-5' ), svg_kses() ); ?>
					</button>


					<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">

						<!-- Main Form Content -->
						<template x-if="!showConfirmationDialog">
							<div class="sm:flex sm:items-start">
								<div class="text-center sm:text-left w-full">
									<?php
									/*
									 * Modal title shows member name + current balance
									 */
									?>
									<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
										<span x-text="member_name ? `Adjust Points - ${member_name}` : '<?php esc_html_e( 'Adjust Points Balance', 'rewardswp' ); ?>'"></span>
									</h3>
									<p class="mt-1 text-sm text-gray-600">
										<?php esc_html_e( 'Current balance:', 'rewardswp' ); ?>
										<strong><span x-text="current_balance.toLocaleString()"></span> <?php esc_html_e( 'points', 'rewardswp' ); ?></strong>
									</p>

									<div class="mt-4 space-y-4">
										<?php
										/*
										* Points Action Segmented Control
										*/
										?>

										<div class="relative w-full max-w-sm mb-6">
											<div class="relative inline-grid items-center justify-center w-full h-10 grid-cols-2 p-1 text-gray-500 bg-gray-100 rounded-lg select-none">
												<button
													x-ref="addButton"
													x-on:click="setAction('add'); repositionMarker($refs.addButton);"
													type="button"
													class="relative z-20 inline-flex items-center justify-center w-full h-8 px-3 text-sm font-medium transition-all rounded-md cursor-pointer whitespace-nowrap"
												>
													<span class="text-green-600 font-semibold mr-1"><?php echo wp_kses( $this->icon_helper->get_icon( 'add-circle', 'w-4 h-4' ), svg_kses() ); ?></span><?php esc_html_e( 'Add Points', 'rewardswp' ); ?>
												</button>
												<button
													x-ref="deductButton"
													x-on:click="setAction('deduct'); repositionMarker($refs.deductButton);"
													type="button"
													class="relative z-20 inline-flex items-center justify-center w-full h-8 px-3 text-sm font-medium transition-all rounded-md cursor-pointer whitespace-nowrap"
												>
													<span class="text-red-600 font-semibold mr-1"><?php echo wp_kses( $this->icon_helper->get_icon( 'subtract-circle', 'w-4 h-4' ), svg_kses() ); ?></span><?php esc_html_e( 'Deduct Points', 'rewardswp' ); ?>
												</button>
												<div x-ref="marker" class="absolute z-10 duration-300 ease-out bg-white rounded-md shadow-sm left-1 top-1" style="width: calc(50% - 2px); height: 32px;">
												</div>
											</div>
										</div>

										<?php
										/*
										* Amount field with validation
										*/
										?>
										<div>
											<label for="points_amount" class="block text-sm font-medium text-gray-700">
												<?php esc_html_e( 'Points amount', 'rewardswp' ); ?>
											</label>
											<div class="mt-1 relative">
												<input
													type="text"
													name="points_amount"
													id="points_amount"
													x-ref="pointsAmountField"
													x-model="adjustPointsAmount"
													x-on:input="touchedAmount = true; validateAmount()"
													x-bind:class="{
														'block w-full px-3 py-2 border border-red-500 rounded-md focus:ring-red-500 focus:border-red-500 sm:text-sm': errorMessage && touchedAmount,
														'block w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 sm:text-sm': !(errorMessage && touchedAmount)
													}"
													placeholder="e.g. 100"
													autocomplete="off"
													inputmode="numeric"
													pattern="^[0-9]*$"
												>
												<template x-if="errorMessage && touchedAmount">
													<div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
														<?php echo wp_kses( $this->icon_helper->get_icon( 'exclamation', 'text-red-500 w-4 h-4' ), svg_kses() ); ?>
													</div>
												</template>
											</div>

											<?php
											/*
											* Error message
											*/
											?>
											<template x-if="errorMessage && touchedAmount">
												<div class="mt-2 text-red-600 text-sm flex items-center gap-1">
													<span x-text="errorMessage"></span>
												</div>
											</template>
										</div>

										<?php
										/*
										* Live "New balance" preview
										*/
										?>
										<template x-if="adjustPointsAmount && !errorMessage && adjustPointsAction">
											<div class="bg-gray-50 rounded-lg p-3" aria-live="polite">
												<div class="text-sm text-gray-700">
													<span><?php esc_html_e( 'New balance:', 'rewardswp' ); ?></span>
													<strong class="text-gray-900">
														<span x-text="getNewBalance().toLocaleString()"></span> <?php esc_html_e( 'points', 'rewardswp' ); ?>
													</strong>
													<span
														x-text="adjustPointsAction === 'add' ? `(+${parseInt(adjustPointsAmount).toLocaleString()})` : `(-${parseInt(adjustPointsAmount).toLocaleString()})`"
														x-bind:class="adjustPointsAction === 'add' ? 'text-green-600' : 'text-red-600'"
														class="ml-1 font-medium"
													></span>
												</div>
											</div>
										</template>

										<?php
										/*
										* Internal note field (required only for deduct)
										*/
										?>
										<div>
											<label for="reason" class="block text-sm font-medium text-gray-700">
												<template x-if="adjustPointsAction === 'deduct'">
													<span><?php esc_html_e( 'Internal note', 'rewardswp' ); ?> <span class="text-red-600">*</span></span>
												</template>
												<template x-if="adjustPointsAction !== 'deduct'">
													<span><?php esc_html_e( 'Internal note', 'rewardswp' ); ?> <span class="text-gray-500"><?php esc_html_e( '(optional)', 'rewardswp' ); ?></span></span>
												</template>
											</label>
											<div class="mt-1">
												<textarea
													id="reason"
													name="reason"
													rows="3"
													x-model="adjustPointsReason"
													x-on:input="touchedReason = true; validateReason()"
													x-bind:class="{
														'block w-full px-3 py-2 border border-red-500 rounded-md focus:ring-red-500 focus:border-red-500 sm:text-sm': reasonError && touchedReason,
														'block w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 sm:text-sm': !(reasonError && touchedReason)
													}"
													x-bind:placeholder="adjustPointsAction === 'deduct' ? 'e.g. Refund – order #1024' : 'e.g. Goodwill credit for delayed order'"
												></textarea>
											</div>
											<template x-if="reasonError && touchedReason">
												<div class="mt-2 text-red-600 text-sm">
													<span x-text="reasonError"></span>
												</div>
											</template>
										</div>
									</div>
								</div>
							</div>

							<?php
							/*
							 * Main Form Buttons
							 */
							?>
						</template>

						<?php
						/*
						 * Confirmation Content
						 */
						?>
						<template x-if="showConfirmationDialog">
							<div class="sm:flex sm:items-start">
							<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'h-10 w-10 text-red-600' ), svg_kses() ); ?>
								<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
									<h3 class="text-lg leading-6 font-medium text-gray-900">
										<?php esc_html_e( 'Confirm Large Deduction', 'rewardswp' ); ?>
									</h3>
									<div class="mt-2">
										<p class="text-sm text-gray-500">
											<span x-text="'<?php
												/* translators: %1$s: number of points to deduct, %2$s: new balance after deduction */
												echo esc_js( __( "You are about to deduct %1\$s points. This will reduce the member's balance to %2\$s points.", 'rewardswp' ) ); ?>'.replace('%1$s', adjustPointsAmount).replace('%2$s', getNewBalance())"></span>
											<?php esc_html_e( 'Are you sure you want to continue?', 'rewardswp' ); ?>
										</p>
									</div>
								</div>
							</div>
						</template>
					</div>

					<?php
					/*
					 * Main Form Buttons
					 */
					?>
					<template x-if="!showConfirmationDialog">
						<div class="px-4 py-3 sm:pt-0 sm:p-6 sm:flex sm:flex-row-reverse">
							<button
								type="button"
								x-on:click="handleAdjustPoints()"
								x-bind:disabled="!isFormValid()"
								x-bind:class="{
									'bg-blue-600 hover:bg-blue-700 focus:ring-blue-500': adjustPointsAction === 'add',
									'bg-red-600 hover:bg-red-700 focus:ring-red-500': adjustPointsAction === 'deduct',
									'opacity-50 cursor-not-allowed': !isFormValid()
								}"
								class="cursor-pointer w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 text-base font-medium text-white focus:outline-none focus:ring-2 focus:ring-offset-2 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
							>
								<span x-text="getCTAText()"></span>
							</button>
							<button
								type="button"
								x-on:click="closeModal()"
								class="cursor-pointer mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
							>
								<?php esc_html_e( 'Cancel', 'rewardswp' ); ?>
							</button>
						</div>
					</template>

					<?php
					/*
					 * Confirmation Buttons
					 */
					?>
					<template x-if="showConfirmationDialog">
						<div class="px-4 py-3 sm:pt-0 sm:p-6 sm:flex sm:flex-row-reverse">
							<button
								type="button"
								x-on:click="confirmAdjustment()"
								class="cursor-pointer w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm"
							>
								<?php esc_html_e( 'Yes, Deduct Points', 'rewardswp' ); ?>
							</button>
							<button
								type="button"
								x-on:click="showConfirmationDialog = false"
								class="cursor-pointer mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
							>
								<?php esc_html_e( 'Cancel', 'rewardswp' ); ?>
							</button>
						</div>
					</template>
				</div>
			</div>

		</div>
		<?php
	}
}
