<?php
/**
 * Add member 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 function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;


/**
 * Add Member Modal View.
 *
 * @since 1.0.0
 */
class AddMemberModalView 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 {
	 *     Optional. An array of arguments.
	 *
	 *     @type string $nonce Nonce for AJAX actions.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$nonce = $args['nonce'] ?? wp_create_nonce( 'rewardswp_add_member_nonce' );

		$alpine_params = [
			'ajaxNonce'   => $nonce,
			'ajaxurl'     => admin_url( 'admin-ajax.php' ),
			'searchNonce' => wp_create_nonce( 'rewardswp_searchable_nonce' ),
			'text'        => [
				'modalTitle'                  => __( 'Add New Member', 'rewardswp' ),
				'modalDescription'            => __( 'Create a new member account', 'rewardswp' ),
				'labelWordPressUser'          => __( 'Select a user', 'rewardswp' ),
				'helpUserSelection'           => __( 'Users who are already members will not be listed.', 'rewardswp' ),
				'validationErrorUserRequired' => __( 'Please select a WordPress user.', 'rewardswp' ),
				'buttonCancel'                => __( 'Cancel', 'rewardswp' ),
				'buttonCreateMember'          => __( 'Create Member', 'rewardswp' ),
				'genericError'                => __( 'An unknown error occurred. Please try again.', 'rewardswp' ),
				'networkError'                => __( 'A network error occurred. Please try again.', 'rewardswp' ),
				'memberCreateSuccess'         => __( 'Member created successfully.', 'rewardswp' ),
				'validationError'             => __( 'Please check the highlighted fields.', 'rewardswp' ),
			],
		];

		?>
		<div
			x-data="addMemberModal(<?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="add-member-modal-title"
			role="dialog"
			aria-modal="true"
			x-cloak
			x-on:keydown.escape.window="closeModal()"
			x-on:open-add-member-modal.window="openModal()"
		>
			<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="closeModal()"
					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="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full z-50"
				>
					<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
						<div class="flex justify-between items-start">
							<div>
								<h3 class="text-lg leading-6 font-medium text-gray-900" id="add-member-modal-title" x-text="text.modalTitle"></h3>
								<p class="text-sm text-gray-500 mt-1" x-text="text.modalDescription"></p>
							</div>
							<button type="button" x-on:click="closeModal()" class="text-gray-400 hover:text-gray-500">
								<?php echo wp_kses( $this->icon_helper->get_icon( 'close', 'w-6 h-6' ), svg_kses() ); ?>
							</button>
						</div>

						<div class="mt-5 space-y-6">
							<!-- WordPress User Selection -->
							<div>
								<label class="block text-sm font-medium text-gray-700 mb-2" x-text="text.labelWordPressUser"></label>
								<?php
								/* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Contents are escaped at the source */
								echo get_view_component(
									'choices',
									[
										'x-model'          => 'selectedUser',
										'selected_options' => 'selectedUser',
										'ref'              => 'addMemberModal',
										'options'          => '[]',
										'ajax_action'      => 'rewardswp_search_users',
										'nonce'            => wp_create_nonce( 'rewardswp_searchable_nonce' ),
										'placeholder'      => esc_html__( 'Enter at least 3 characters to search', 'rewardswp' ),
										'required'         => true,
										'required_ref'     => 'userSelectionError',
										'error_message'    => esc_html__( 'Please select a WordPress user', 'rewardswp' ),
									]
								);
								?>
								<p class="mt-2 text-sm text-gray-500" x-text="text.helpUserSelection"></p>
							</div>



						</div>
					</div>

					<!-- General Error Message -->
					<template x-if="generalError">
						<div class="px-4 pb-3">
							<div class="bg-red-50 border border-red-200 rounded-md p-3">
								<p class="text-sm text-red-700" x-text="generalError"></p>
							</div>
						</div>
					</template>

					<!-- Modal Footer -->
					<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
						<button
							type="button"
							x-on:click="createMember()"
							x-bind:disabled="isSubmitting || !selectedUser || selectedUser.length === 0"
							x-bind:class="{
								'cursor-not-allowed opacity-90': isSubmitting || (!selectedUser || selectedUser.length === 0),
								'cursor-pointer': !isSubmitting && selectedUser && selectedUser.length > 0
							}"
							class="w-full 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 min-w-[120px] grid grid-cols-1 grid-rows-1 [grid-template-areas:stack] place-items-center text-center"
						>
							<span
								class="[grid-area:stack] transition-opacity duration-200"
								x-bind:class="{ 'invisible': isSubmitting, 'visible': !isSubmitting }"
								x-text="text.buttonCreateMember"
							></span>
							<svg
								class="animate-spin h-5 w-5 [grid-area:stack] transition-opacity duration-200 invisible"
								x-bind:class="{ 'invisible': isSubmitting !== true, 'visible': isSubmitting === true }"
								xmlns="http://www.w3.org/2000/svg"
								fill="none"
								viewBox="0 0 24 24"
							>
								<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
								<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
							</svg>
							<svg
								class="h-5 w-5 [grid-area:stack] transition-opacity duration-200 invisible"
								x-bind:class="{ 'invisible': isSubmitting !== 'complete', 'visible': isSubmitting === 'complete' }"
								xmlns="http://www.w3.org/2000/svg"
								fill="none"
								viewBox="0 0 24 24"
								stroke="currentColor"
							>
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
							</svg>
						</button>
						<button
							type="button"
							x-on:click="closeModal()"
							x-bind:disabled="isSubmitting"
							class="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 disabled:opacity-50"
							x-text="text.buttonCancel"
						></button>
					</div>
				</div>
			</div>
		</div>

		<script>
		function addMemberModal(params) {
			return {
				text: params.text,
				ajaxurl: params.ajaxurl,
				ajaxNonce: params.ajaxNonce,
				searchNonce: params.searchNonce,

				// Form data.
				selectedUser: [],

				// State.
				showModal: false,
				isSubmitting: false,
				errors: {},
				generalError: '',
				userSelectionError: false, // Para validação do ChoicesComponentView

				openModal() {
					this.showModal = true;
				},

				closeModal() {
					// Reset form data.
					this.selectedUser = [];
					this.errors = {};
					this.generalError = '';
					this.isSubmitting = false;
					this.userSelectionError = false;

					// Close modal.
					this.showModal = false;
				},

				// Watch for user selection.
				init() {
					this.$watch('selectedUser', (newValue) => {
						if (newValue && newValue.length > 0) {
							// Clear any existing errors when user is selected.
							this.errors.selectedUser = '';
							this.generalError = '';
						}
					});
				},

				validateForm() {
					this.errors = {};

					// Note: WordPress user selection validation is handled by ChoicesComponentView.
					// No additional validation needed here since the component shows its own error message.
					return Object.keys(this.errors).length === 0;
				},

				validateChoicesComponent() {
					// Trigger validation by dispatching event to ChoicesComponentView.
					this.$dispatch('validate-choices');
				},

				async createMember() {
					// Trigger validation on ChoicesComponentView.

					this.validateChoicesComponent();

					// Check if user is selected (ChoicesComponentView handles the visual feedback).
					if (!this.selectedUser || this.selectedUser.length === 0) {
						this.generalError = this.text.validationError;
						return;
					}

					// Validate other form fields.
					if (!this.validateForm()) {
						this.generalError = this.text.validationError;
						return;
					}

					this.isSubmitting = true;
					this.generalError = '';

					const formData = new FormData();
					formData.append('action', 'rewardswp_add_member');
					formData.append('nonce', this.ajaxNonce);
					formData.append('user_id', this.selectedUser[0].id);

					try {
						const response = await fetch(this.ajaxurl, {
							method: 'POST',
							body: formData
						});

						if (!response.ok) {
							throw new Error(this.text.networkError);
						}

						const result = await response.json();

						if (result.success) {
							// Show success state.
							this.isSubmitting = 'complete';

							// Wait a moment to show the success state, then redirect.
							setTimeout(() => {
								const memberViewUrl = `admin.php?page=rewardswp-members&action=view_member&member_id=${result.data.member_id}&rewardswp_message=member_created_successfully`;
								window.location.href = memberViewUrl;
							}, 1000);
						} else {
							// Handle specific validation errors.
							if (result.data && result.data.field_errors) {
								this.errors = result.data.field_errors;
								this.generalError = this.text.validationError;
							} else {
								this.generalError = result.data?.message || this.text.genericError;
							}
							this.isSubmitting = false;
						}
					} catch (error) {
						console.error('Error creating member:', error);
						this.generalError = this.text.networkError;
						this.isSubmitting = false;
					}
				}
			};
		}
		</script>
		<?php
	}
}
