<?php
/**
 * Delete 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\svg_kses;

class DeleteMemberModalView 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 Arguments, not used directly in this modal as data is passed via Alpine event.
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$alpine_params = [
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'text'    => [
				'modalTitle'       => __( 'Delete Member', 'rewardswp' ),
				'confirmationText' => __( 'Are you sure you want to delete this member? This action cannot be undone.', 'rewardswp' ),
				'warningText'      => __( 'Deleting this member will remove all their data including points, referrals, and activity history.', 'rewardswp' ),
				'buttonCancel'     => __( 'Cancel', 'rewardswp' ),
				'buttonDelete'     => __( 'Delete Member', 'rewardswp' ),
				'buttonDeleting'   => __( 'Deleting...', 'rewardswp' ),
				'genericError'     => __( 'An unknown error occurred. Please try again.', 'rewardswp' ),
				'networkError'     => __( 'A network error occurred. Please try again.', 'rewardswp' ),
				'deleteError'      => __( 'Could not delete member. Please try again.', 'rewardswp' ),
			],
		];

		?>
		<div
			x-data="{
				showModal: false,
				memberId: null,
				ajaxNonce: '',
				isLoading: false,
				ajaxurl: '<?php echo esc_js( $alpine_params['ajaxurl'] ); ?>',
				text: <?php echo esc_attr( wp_json_encode( $alpine_params['text'] ) ); ?>,
				init() {
					window.addEventListener('open-delete-member-modal', (event) => {
						this.memberId = event.detail.memberId;
						this.ajaxNonce = event.detail.nonce;
						this.isLoading = false;
						this.showModal = true;
					});
				},
				handleDeleteMember() {
					if (!this.memberId || this.isLoading) return;
					this.isLoading = true;

					const formData = new FormData();
					formData.append('action', 'rewardswp_delete_member_from_detail');
					formData.append('nonce', this.ajaxNonce);
					formData.append('member_id', this.memberId);

					fetch(this.ajaxurl, {
						method: 'POST',
						body: formData
					})
					.then(response => response.json())
					.then(result => {
						if (result.success && result.data.redirect_url) {
							// The toast will be shown on the redirected page via query param
							window.location.href = result.data.redirect_url;
							// No need to hide modal or set isLoading = false as page will redirect
						} else {
							window.dispatchEvent(new CustomEvent('rewardswp-toast', {
								detail: { message: result.data.message || this.text.deleteError, type: 'error' }
							}));
							this.isLoading = false;
						}
					})
					.catch(error => {
						console.error('Error deleting member:', error);
						window.dispatchEvent(new CustomEvent('rewardswp-toast', {
							detail: { message: this.text.networkError, type: 'error' }
						}));
						this.isLoading = false;
					});
				}
			}"
			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="delete-member-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 sm:max-w-md sm:w-full z-50"
				>
					<!-- Close button -->
					<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="px-6 pt-5 pb-6">
						<div class="flex items-start gap-3">
							<div class="flex-shrink-0 mt-0.5">
								<?php echo wp_kses( $this->icon_helper->get_icon( 'alert-triangle', 'w-6 h-6 text-red-500' ), svg_kses() ); // Red icon for delete confirmation ?>
							</div>
							<div class="flex-1">
								<h3 class="text-lg leading-6 font-semibold text-gray-900" id="delete-member-modal-title" x-text="text.modalTitle"></h3>
								<p class="mt-2 text-sm text-gray-600" x-text="text.confirmationText"></p>
							</div>
						</div>
						<div class="mt-4 bg-red-50 border border-red-200 rounded-md p-4">
							<p class="text-sm text-red-700" x-text="text.warningText"></p>
						</div>
					</div>

					<div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse">
						<button
							type="button"
							x-on:click="handleDeleteMember()"
							x-bind:disabled="isLoading"
							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 disabled:opacity-60 disabled:cursor-not-allowed"
						>
							<span x-show="!isLoading" x-text="text.buttonDelete"></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() ); ?>
								<span x-text="text.buttonDeleting"></span>
							</span>
						</button>
						<button
							type="button"
							x-on:click="showModal = false"
							x-bind:disabled="isLoading"
							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 disabled:opacity-75 disabled:cursor-not-allowed"
						>
							<span x-text="text.buttonCancel"></span>
						</button>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}
