<?php
/**
 * Toggle 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 Awesomemotive\Rewardswp\Services\OptionsService;

class ToggleComponentView 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,
			[
				'section'             => '',
				'name'                => '',
				'label'               => '',
				'is_checked'          => false,
				'x-on:click'          => '',
				'on_click'            => '',
				'disabled'            => false,
				'x-bind:disabled'     => '',
				'locked'              => false,
				'locked_message'      => '',
				'locked_click_action' => '',
				'no_input'            => false,
				'x_model'             => '',
				'button_align'        => 'left',
			]
		);

		// Prioritize 'x-on:click' but fall back to 'on_click' for backward compatibility.
		$click_event = ! empty( $args['x-on:click'] ) ? $args['x-on:click'] : $args['on_click'];

		if ( $args['locked'] && ! empty( $args['locked_click_action'] ) ) {
			$click_directive = $args['locked_click_action'];
		} elseif ( $args['locked'] ) {
			$click_directive = '';
		} else {
			$click_directive = $click_event;
		}

		$toggle_expression = '';
		if ( ! $args['locked'] ) {
			if ( ! empty( $args['x_model'] ) ) {
				$toggle_expression = sprintf( '%1$s = !%1$s;', $args['x_model'] );
			} else {
				$toggle_expression = 'toggleEnabled = !toggleEnabled;';
			}
		}

		$click_parts = [];
		if ( '' !== $toggle_expression ) {
			$click_parts[] = $toggle_expression;
		}
		if ( ! empty( $click_directive ) ) {
			$click_parts[] = $click_directive;
		}

		$click_attribute = trim( implode( ' ', $click_parts ) );

		// Split the name into parts if it contains brackets.
		$name_parts = explode( '[', str_replace( ']', '', $args['name'] ) );

		// Build the ID attribute.
		$id = OptionsService::OPTION_NAME;

		if ( ! empty( $args['section'] ) ) {
			$id .= '[' . $args['section'] . ']';
		}

		foreach ( $name_parts as $part ) {
			$id .= '[' . $part . ']';
		}

		$x_model_expr = empty( $args['x_model'] ) ? 'toggleEnabled' : $args['x_model'];
		$x_model_expr = empty( $args['x_model'] ) ? 'toggleEnabled' : $args['x_model'];

		?>

		<div class="flex flex-col gap-2">
			<div
				<?php echo empty( $args['x_model'] ) ? 'x-data="{ toggleEnabled: ' . wp_json_encode( (bool) $args['is_checked'] ) . ' }"' : ''; ?>
				class="flex items-center"
			>
				<?php
				$has_dynamic_disabled = ! empty( $args['x-bind:disabled'] );
				$dynamic_disabled_expr = $has_dynamic_disabled ? $args['x-bind:disabled'] : 'false';
				?>
				<button
					<?php if ( ! empty( $args['x-bind:id'] ) ) : ?>
						x-bind:id="<?php echo esc_attr( $args['x-bind:id'] ); ?>"
					<?php else : ?>
						id="<?php echo esc_attr( $id ); ?>"
					<?php endif; ?>
					type="button"
					<?php if ( '' !== $click_attribute ) : ?>
						x-on:click="<?php echo esc_attr( $click_attribute ); ?>"
					<?php endif; ?>
					<?php if ( $has_dynamic_disabled ) : ?>
						x-bind:disabled="<?php echo esc_attr( $dynamic_disabled_expr ); ?>"
					<?php endif; ?>
					x-bind:class="{
						'bg-blue-600': <?php echo esc_attr( $x_model_expr ); ?>,
						'bg-gray-200': <?php echo esc_attr( sprintf( '!%s', $x_model_expr ) ); ?>,
						'opacity-50': <?php echo $args['locked'] ? 'true' : esc_attr( $dynamic_disabled_expr ); ?>,
						'cursor-not-allowed': <?php echo ( $args['locked'] && empty( $args['locked_click_action'] ) ) ? 'true' : esc_attr( $dynamic_disabled_expr ); ?>,
						'cursor-pointer': <?php echo ( ! $args['locked'] || ! empty( $args['locked_click_action'] ) ) ? ( $has_dynamic_disabled ? '!' . esc_attr( $dynamic_disabled_expr ) : 'true' ) : 'false'; ?>,
						'ml-auto': <?php echo 'right' === $args['button_align'] ? 'true' : 'false'; ?>
					}"
					class="relative inline-flex flex-shrink-0 h-6 transition-colors duration-200 ease-in-out border-2 border-transparent rounded-full w-11 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
					role="switch"
					x-bind:aria-checked="<?php echo esc_attr( sprintf( '%s.toString()', $x_model_expr ) ); ?>"
					<?php echo ( $args['locked'] && empty( $args['locked_click_action'] ) ) ? 'disabled' : ''; ?>
				>
					<span class="sr-only"><?php echo esc_html( $args['label'] ); ?></span>
					<span
						x-bind:class="<?php echo esc_attr( sprintf( "%s ? 'translate-x-5' : 'translate-x-0'", $x_model_expr ) ); ?>"
						class="relative inline-block w-5 h-5 transition duration-200 ease-in-out transform bg-white rounded-full shadow pointer-events-none ring-0"
					>
						<span
							x-bind:class="<?php echo esc_attr( sprintf( "%s ? 'opacity-0' : 'opacity-100'", $x_model_expr ) ); ?>"
							class="absolute inset-0 flex items-center justify-center w-full h-full transition-opacity duration-100 ease-out"
							aria-hidden="true"
						>
							<svg class="w-3 h-3 text-gray-400" fill="none" viewBox="0 0 12 12">
								<path d="M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
							</svg>
						</span>
						<span
							x-bind:class="<?php echo esc_attr( sprintf( "%s ? 'opacity-100' : 'opacity-0'", $x_model_expr ) ); ?>"
							class="absolute inset-0 flex items-center justify-center w-full h-full transition-opacity duration-200 ease-in"
							aria-hidden="true"
						>
							<svg class="w-3 h-3 text-blue-600" fill="currentColor" viewBox="0 0 12 12">
								<path d="M3.707 5.293a1 1 0 00-1.414 1.414l1.414-1.414zM5 8l-.707.707a1 1 0 001.414 0L5 8zm4.707-3.293a1 1 0 00-1.414-1.414l1.414 1.414zm-7.414 2l2 2 1.414-1.414-2-2-1.414 1.414zm3.414 2l4-4-1.414-1.414-4 4 1.414 1.414z" />
							</svg>
						</span>
					</span>
				</button>

				<?php if ( ! $args['no_input'] ) : ?>
				<input
					type="hidden"
					name="<?php echo esc_attr( $id ); ?>"
					x-bind:value="<?php echo esc_attr( sprintf( '%s ? 1 : 0', $x_model_expr ) ); ?>">
				<?php endif; ?>
			</div>

			<?php if ( $args['locked'] && $args['locked_message'] ) : ?>
				<p class="!mt-1 !mb-0 !text-sm text-gray-500">
					<?php echo esc_html( $args['locked_message'] ); ?>
				</p>
			<?php endif; ?>

		</div>

		<?php
	}
}
