<?php
/**
 * Choices component view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Components
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Components;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use function Awesomemotive\Rewardswp\Helpers\array_to_json;
use function Awesomemotive\Rewardswp\Helpers\tag_attr;


/**
 * Choices Component View.
 *
 * @since 1.0.0
 */
class ChoicesComponentView extends AbstractView implements ViewInterface {
	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$args = wp_parse_args(
			$args,
			[
				'name'             => '',
				'ref'              => 'root',
				'x-model'          => '',
				'options'          => [],
				'selected_options' => [],
				'multiple'         => false,
				'min_query_length' => 3,
				'debounce_delay'   => 300,
				'ajax_action'      => '',
				'nonce'            => '',
				'placeholder'      => esc_html__( 'Start typing to search...', 'rewardswp' ),
				'required'         => false,
				'required_ref'     => '',
				'error_message'    => esc_html__( 'Please select a product', 'rewardswp' ),
			]
		);

		if ( empty( $args['name'] ) && empty( $args['x-model'] ) ) {
			esc_html_e( 'Failed to render the choices component, you need to specify at least one of these arguments: name, x-model.', 'rewardswp' );
			return;
		}

		?>

		<div x-data="choicesComponent(<?php echo array_to_json( $args, true, true ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>)" class="relative" @validate-choices.window="validate()">
			<div
				class="relative flex flex-wrap items-center px-2 py-2 rounded-md bg-white px-3 outline-1 -outline-offset-1 focus-within:outline-2 focus-within:-outline-offset-2"
				x-bind:class="{
					'text-red-900 outline-red-300 focus-within:outline-red-600': hasErrors,
					'outline-gray-300 focus-within:outline-blue-600': !hasErrors
				}"
			>
				<template x-for="item in selected" x-bind:key="item.id">
					<span class="bg-gray-200 text-gray-800 px-2 py-1 rounded mr-1 flex items-center">
						<span x-html="item.name" class="mr-1"></span>
						<button x-on:click="remove(item)" class="text-gray-800 cursor-pointer">&times;</button>
						</span>
				</template>
				<input
					type="text"
					x-model="query"
					x-ref="searchField"
					x-on:input="search"
					x-on:click.outside="showResults = false"
					x-bind:placeholder="selected.length === 0 ? '<?php echo esc_attr( $args['placeholder'] ); ?>' : ''"
					class="flex-1 focus:outline-none block min-w-0 grow text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-sm/6"
				/>
				<svg
					x-show="hasErrors"
					class="pointer-events-none size-5 text-red-500 ml-2 flex-shrink-0"
					viewBox="0 0 16 16"
					fill="currentColor"
					aria-hidden="true"
				>
					<path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14ZM8 4a.75.75 0 0 1 .75.75v3a.75.75 0 0 1-1.5 0v-3A.75.75 0 0 1 8 4Zm0 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z" clip-rule="evenodd" />
				</svg>
				<input
					type="hidden"
					<?php tag_attr( 'name', $args['name'] ); ?>
					<?php
					if ( ! empty( $args['name'] && empty( $args['x-model'] ) ) ) {
						tag_attr( 'x-bind:value', 'JSON.stringify(selectedIds)' );
					}
					?>
				/>
			</div>
			<ul
				class="absolute bg-white border rounded mt-1 w-full max-h-40 overflow-auto z-10"
				x-show="showResults && results.length"
				x-on:click.outside="showResults = false"
			>
				<template x-for="result in results" x-bind:key="result.id">
					<li
						x-on:click="select(result)"
						class="p-2 hover:bg-gray-200 cursor-pointer"
						x-bind:class="selected.some(item =&gt; item.id === result.id) ? 'text-gray-400 cursor-not-allowed' : ''"
						x-bind:disabled="selected.some(item =&gt; item.id === result.id)"
						x-html="result.highlightedName"
					></li>
				</template>
			</ul>
			<p x-show="hasErrors" class="text-red-600 text-sm mt-2"><?php echo esc_html( $args['error_message'] ); ?></p>
		</div>

		<?php
	}
}
