<?php
/**
 * Update referral code 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\get_referral_link_base_url;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

// For nonce consistency if needed

class UpdateReferralCodeModalView extends AbstractView implements ViewInterface {
	/**
	 * Icon helper instance.
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

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

	/**
	 * Render the template.
	 *
	 * @param array $args {
	 *     Required. An array of arguments.
	 *
	 *     @type int    $member_id The member ID.
	 *     @type string $current_referral_code The member's current referral code.
	 *     @type string $nonce     Nonce for AJAX actions.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		// Default to generic modal name, can be overridden for specific instances (like in list tables).
		$alpine_component_name = $args['alpine_component_name'] ?? 'updateReferralCodeModal';

		// Set sensible defaults for when the modal is rendered without specific data (e.g., in a list view).
		// The actual data will be passed via an Alpine.js event.
		$member_id             = absint( $args['member_id'] ?? 0 );
		$current_referral_code = sanitize_text_field( $args['current_referral_code'] ?? '' );
		$ajax_nonce            = sanitize_text_field( $args['nonce'] ?? '' ); // This should be specific to this modal's actions.

		$alpine_params = [
			'memberId'            => $member_id,
			'initialReferralCode' => $current_referral_code,
			'ajaxNonce'           => $ajax_nonce,
			'ajaxurl'             => admin_url( 'admin-ajax.php' ),
			'referralLinkBase'    => get_referral_link_base_url(),
			'text'                => [
				'modalTitle'                 => __( 'Update referral link', 'rewardswp' ),
				'inputDescription'           => __( 'Edit the referral code or generate a new one', 'rewardswp' ),
				'labelReferralCode'          => __( 'Referral Code', 'rewardswp' ),
				'inputPlaceholder'           => __( 'e.g. zo6mhz1', 'rewardswp' ),
				'regenerateTooltip'          => __( 'Generate random code', 'rewardswp' ),
				/* translators: %1$s and %2$s are opening and closing HTML tags for bold formatting */
				'warningText'                => sprintf( __( '%1$sChanging this code%2$s updates the link and disables any links previously shared.', 'rewardswp' ), '<span class="text-amber-700 font-semibold">', '</span>' ),
				'buttonCancel'               => __( 'Cancel', 'rewardswp' ),
				'buttonUpdate'               => __( 'Update link', 'rewardswp' ),
				'genericError'               => __( 'An unknown error occurred. Please try again.', 'rewardswp' ),
				'networkError'               => __( 'A network error occurred. Please try again.', 'rewardswp' ),
				'codeUpdatedSuccess'         => __( 'Referral code updated successfully.', 'rewardswp' ),
				'validationErrorNumericCode' => __( 'Referral code cannot be numeric only.', 'rewardswp' ),
			],
		];

		?>
		<div
			x-data="<?php echo esc_attr( $alpine_component_name ); ?>(<?php echo esc_attr( wp_json_encode( $alpine_params ) ); ?>)"
			x-show="showModal"
			x-trap.inert.noscroll="showModal"
			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="update-referral-code-modal-title"
			role="dialog"
			aria-modal="true"
			x-cloak
			x-on:keydown.escape.window="showModal = false"
		>
			<div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
				<!-- Background overlay -->
				<div
					x-show="showModal"
					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="showModal = false"
					aria-hidden="true"
				>
					<div class="absolute inset-0 bg-slate-900/40"></div>
				</div>

				<!-- Modal panel -->
				<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
				<div
					x-show="showModal"
					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 w-full max-w-sm sm:w-auto sm:max-w-none sm:min-w-96 z-50"
				>
					<!-- Close button positioned in top-right corner -->
					<button
						type="button"
						x-on:click="showModal = false"
						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">
						<div>
							<h3 class="text-lg leading-6 font-medium text-gray-900 pr-8" id="update-referral-code-modal-title" x-text="text.modalTitle"></h3>
							<p class="mt-2 text-sm text-gray-600" x-text="text.inputDescription"></p>
						</div>

						<div class="mt-6">
							<div
								class="flex rounded-md bg-white outline-1 -outline-offset-1 outline-gray-200"
								x-bind:class="{ 'outline-red-500 outline-2': errorMessage }"
							>
								<span class="flex select-none items-center pl-5 text-gray-500 sm:text-base min-w-fit" x-text="referralLinkBase"></span>
								<input
									type="text"
									name="referral_code_input"
									id="referral_code_input"
									x-model="referralCode"
									x-bind:placeholder="text.inputPlaceholder"
									x-on:input="validateCode"
									class="block min-w-0 flex-1 py-3 px-3 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-base/6 font-mono"
									x-on:focus="$event.target.select()"
									x-ref="referralCodeInput"
									x-init="$watch('showModal', (value) => { if (value) { $nextTick(() => { $refs.referralCodeInput.focus(); $refs.referralCodeInput.select(); }) } })"
								>
								<div class="flex py-3 pr-5">
									<button
										type="button"
										x-on:click="isGenerating = true; generateRandomCode(); setTimeout(() => isGenerating = false, 300)"
										x-bind:title="text.regenerateTooltip"
										class="cursor-pointer text-gray-500 hover:text-blue-600 transition-all duration-200 items-center inline-flex"
										x-data="{ isGenerating: false }"
									>
										<span x-bind:class="{ 'transform -rotate-180 transition-transform duration-300 text-blue-600': isGenerating }" class="inline-block">
											<?php echo wp_kses( $this->icon_helper->get_icon( 'refresh', 'w-5 h-5' ), svg_kses() ); ?>
										</span>
									</button>
								</div>
							</div>

							<template x-if="errorMessage">
								<p class="mt-2 text-sm text-red-600" x-text="errorMessage"></p>
							</template>
						</div>

						<div 
							x-show="referralCode !== initialReferralCode"
							x-transition:enter="transition ease-out duration-300"
							x-transition:enter-start="opacity-0 scale-95"
							x-transition:enter-end="opacity-100 scale-100"
							x-transition:leave="transition ease-in duration-200"
							x-transition:leave-start="opacity-100 scale-100"
							x-transition:leave-end="opacity-0 scale-95"
							class="mt-4 flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm"
						>
							<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'h-4 w-4 text-amber-700 shrink-0 mt-[2px]' ), svg_kses() ); ?>
							<p class="text-amber-800 break-words overflow-wrap-anywhere min-w-0" x-html="text.warningText"></p>
						</div>
					</div>
					<div class="px-4 py-3 sm:pt-0 sm:p-6 sm:flex sm:flex-row-reverse">
						<button
							type="button"
							x-on:click="handleUpdateReferralCode()"
							x-bind:disabled="isLoading || !isCodeValid || errorMessage || (referralCode === initialReferralCode)"
							class="cursor-pointer w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-60 disabled:cursor-not-allowed"
						>
							<span x-show="!isLoading" x-text="text.buttonUpdate"></span>
							<span x-show="isLoading">
								<?php echo wp_kses( $this->icon_helper->get_icon( 'loader', 'animate-spin -ml-1 mr-3 h-5 w-5 text-white' ), svg_kses() ); ?>
								<?php esc_html_e( 'Updating...', 'rewardswp' ); ?>
							</span>
						</button>
						<button
							type="button"
							x-on:click="showModal = 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:w-auto sm:text-sm"
						>
							<span x-text="text.buttonCancel"></span>
						</button>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}
