<?php
/**
 * Drawer 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\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Views\Admin\Parts\DrawerSummaryView;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\kses;

/**
 * Drawer component for editing features like actions and rewards.
 *
 * Provides a slide-in drawer from the right with form-optimized layout,
 * validation error display, and unsaved changes detection.
 *
 * @since 1.1.0
 */
class DrawerComponentView extends AbstractView implements ViewInterface {

	/**
	 * Views factory instance.
	 *
	 * @since 1.1.0
	 *
	 * @var ViewsFactory
	 */
	private ViewsFactory $views_factory;

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 *
	 * @param ViewsFactory $views_factory Views factory instance.
	 */
	public function __construct( ViewsFactory $views_factory ) {
		$this->views_factory = $views_factory;
	}

	/**
	 * Render the form drawer component.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     Optional. Array of drawer arguments.
	 *
	 *     @type string $alpine_var        The Alpine.js variable name for the drawer state. Default 'drawer'.
	 *     @type string $content_callback  The callback method to render drawer content.
	 *     @type array  $content_args      Arguments to pass to the content callback.
	 * }
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$args = wp_parse_args(
			$args,
			[
				'alpine_var'       => 'drawer',
				'content_callback' => null,
				'content_args'     => [],
			]
		);

		$alpine_var        = esc_attr( $args['alpine_var'] );
		$alpine_store      = esc_js( $args['alpine_var'] );
		$store_reference   = sprintf( '$store.%s', $alpine_store );
		$store_is_open_raw = sprintf( '%s.isOpen', $store_reference );
		$store_close_raw   = sprintf( '%s.close()', $store_reference );
		$store_type_raw    = sprintf( '%s.type', $store_reference );
		$store_is_new_raw  = sprintf( '%s.isNew', $store_reference );
		$store_is_upgrade  = sprintf( '%s.isUpgrade', $store_reference );
		$store_view_raw    = sprintf( '%s.view', $store_reference );
		$store_is_loading  = sprintf( '%s.isLoading', $store_reference );
		$store_add_title   = sprintf( '%s.addTitle', $store_reference );
		$store_has_changes = sprintf( '%s.hasChanges()', $store_reference );
		?>

		<!-- Backdrop -->
		<div x-cloak
			x-show="<?php echo esc_attr( $store_is_open_raw ); ?>"
			class="fixed inset-x-0 z-40 bg-slate-900/40"
			style="top: var(--wp-admin--admin-bar--height, 32px); height: calc(100vh - var(--wp-admin--admin-bar--height, 32px));"
			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"
			x-on:click="<?php echo esc_attr( $store_close_raw ); ?>">
		</div>

		<!-- Drawer Panel -->
		<div x-cloak
			x-show="<?php echo esc_attr( $store_is_open_raw ); ?>"
			x-on:click="<?php echo esc_attr( $store_close_raw ); ?>"
			class="fixed right-0 z-50 flex max-w-full pl-10 sm:pl-16"
			x-transition:enter="transform transition ease-in-out duration-300"
			x-transition:enter-start="translate-x-full"
			x-transition:enter-end="translate-x-0"
			x-transition:leave="transform transition ease-in duration-200"
			x-transition:leave-start="translate-x-0"
			x-transition:leave-end="translate-x-full"
			x-on:keydown.escape.window="<?php echo esc_attr( $store_close_raw ); ?>"
			style="top: var(--wp-admin--admin-bar--height, 32px); height: calc(100vh - var(--wp-admin--admin-bar--height, 32px));">
			<div class="h-full w-screen max-w-xl pl-10 sm:pl-16">
					<div x-on:click.stop class="flex h-full flex-col overflow-hidden bg-white shadow-2xl" role="document">
						<!-- Header -->
						<div class="bg-gradient-to-r from-blue-600 to-blue-700 px-6 py-4">
							<div class="flex items-start justify-between">
								<div>
									<h2 class="text-lg font-semibold text-white"
										x-text="<?php echo esc_attr( sprintf( '%s.title', $store_reference ) ); ?>">
									</h2>
									<p class="mt-1 text-sm text-blue-100"
										x-text="<?php echo esc_attr( sprintf( '%s.subtitle', $store_reference ) ); ?>"
										x-show="<?php echo esc_attr( sprintf( '%s.subtitle', $store_reference ) ); ?>">
									</p>
								</div>
								<button type="button"
										x-on:click="<?php echo esc_attr( $store_close_raw ); ?>"
										class="rounded-md bg-blue-600 p-1.5 text-blue-200 hover:bg-blue-500 hover:text-white transition-colors focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-blue-600">
									<span class="sr-only"><?php esc_html_e( 'Close drawer', 'rewardswp' ); ?></span>
									<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
										<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
									</svg>
								</button>
							</div>
						</div>

						<!-- Validation Errors Banner -->
						<div x-show="<?php echo esc_attr( sprintf( 'Object.keys(%s.errors || {}).length > 0', $store_reference ) ); ?>"
							x-collapse
							class="border-l-4 border-red-400 bg-red-50 p-4">
							<div class="flex">
								<div class="flex-shrink-0">
									<svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
										<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
									</svg>
								</div>
								<div class="ml-3">
									<p class="text-sm font-medium text-red-800">
										<?php esc_html_e( 'Please correct the following errors:', 'rewardswp' ); ?>
									</p>
									<ul class="mt-2 list-disc list-inside text-sm text-red-700">
										<template x-for="(error, field) in <?php echo esc_attr( sprintf( '%s.errors', $store_reference ) ); ?>" x-bind:key="field">
											<li x-text="error"></li>
										</template>
									</ul>
								</div>
							</div>
						</div>

						<!-- Scrollable Content Area -->
		<div class="flex-1 overflow-y-auto">
			<div class="px-6 py-6 space-y-6 h-full" id="<?php echo esc_attr( $args['alpine_var'] . '-content' ); ?>">
				<?php
				// Render dynamic content if callback provided.
				if ( is_callable( $args['content_callback'] ) ) {
					call_user_func( $args['content_callback'], $args['content_args'] );
				}
				?>
					</div>
				</div>

				<!-- Drawer Summary Section (fixed position above footer) -->
				<?php
				$drawer_summary_view = $this->views_factory->get_view( DrawerSummaryView::class );
				if ( $drawer_summary_view instanceof DrawerSummaryView ) {
					$drawer_summary_view->render();
				}
				?>

				<!-- Footer -->
						<div class="flex-shrink-0 border-t border-gray-200 px-6 py-4"
							x-data="{ confirmDelete: false }"
							x-init="<?php echo esc_attr( sprintf( "\$watch('%s.isOpen', (isOpen) => { if (!isOpen) { confirmDelete = false; } })", $store_reference ) ); ?>">
							<div class="flex items-center justify-between">
								<!-- Left side: Delete button for redeem actions -->
								<div class="flex flex-col gap-2">
									<!-- Remove button (for redeem actions, earn actions, and referral rewards) -->
								<button
									type="button"
									x-show="<?php echo esc_attr( sprintf(
										"(%1\$s === 'spend' || %1\$s === 'earn' || (%1\$s && %1\$s.startsWith('referral'))) && !%2\$s && !%3\$s && !confirmDelete",
										$store_type_raw,
										$store_is_new_raw,
										$store_is_upgrade
									) ); ?>"
									x-on:click="confirmDelete = true"
										class="text-sm font-medium text-gray-600 hover:text-red-600 transition-colors cursor-pointer"
									>
										<?php esc_html_e( 'Remove', 'rewardswp' ); ?>
									</button>

									<!-- Confirmation prompt -->
									<div x-show="confirmDelete" class="flex items-center gap-2 text-sm font-medium text-gray-700">
										<span><?php esc_html_e( 'Are you sure?', 'rewardswp' ); ?></span>
										<!-- Yes link -->
										<button
											type="button"
											x-on:click="<?php echo esc_attr( str_replace(
												'{store}',
												$store_reference,
												"(() => {
												if ({store}.type === 'spend') {
													if ({store}.actionId) {
														\$dispatch('remove-spend-action', { actionId: {store}.actionId });
														confirmDelete = false;
														{store}.close(true);
													}
												} else if ({store}.type === 'earn') {
													if ({store}.actionId) {
														\$dispatch('remove-earn-action', { actionId: {store}.actionId });
														confirmDelete = false;
														{store}.close(true);
													}
												} else if ({store}.type && {store}.type.startsWith('referral')) {
													if ({store}.actionId) {
														window.dispatchEvent(new CustomEvent('remove-referral-reward', {
															detail: { context: {store}.actionId }
														}));
														confirmDelete = false;
														{store}.close(true);
													}
												}
											})()"
											) ); ?>"
											class="cursor-pointer text-red-600 hover:text-red-700 hover:underline transition-colors"
										>
											<?php esc_html_e( 'Yes', 'rewardswp' ); ?>
										</button>
										<!-- No link -->
										<button
											type="button"
											x-on:click="confirmDelete = false"
											class="cursor-pointer text-gray-600 hover:text-gray-900 hover:underline transition-colors"
										>
											<?php esc_html_e( 'No', 'rewardswp' ); ?>
										</button>
									</div>
								</div>

								<!-- Action buttons -->
								<div class="flex gap-3">
									<button type="button"
											x-on:click="<?php echo esc_attr( $store_close_raw ); ?>"
											class="cursor-pointer rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors">
										<span x-show="<?php echo esc_attr( sprintf( "%s === 'export' && %s", $store_type_raw, $store_is_upgrade ) ); ?>"><?php esc_html_e( 'Not now', 'rewardswp' ); ?></span>
										<span x-show="<?php echo esc_attr( sprintf( "!(%s === 'export' && %s)", $store_type_raw, $store_is_upgrade ) ); ?>"><?php esc_html_e( 'Cancel', 'rewardswp' ); ?></span>
									</button>

									<!-- Save button (for regular features) -->
									<button type="button"
											x-show="<?php echo esc_attr( sprintf(
												'%s && %s === \'config\' && !%s',
												$store_is_open_raw,
												$store_view_raw,
												$store_is_upgrade
											) ); ?>"
											x-cloak
											x-on:click="<?php echo esc_attr( sprintf( '%s.save()', $store_reference ) ); ?>"
											x-bind:disabled="<?php echo esc_attr( sprintf(
												'%s || (!%s && !%s)',
												$store_is_loading,
												$store_is_new_raw,
												$store_has_changes
											) ); ?>"
											class="cursor-pointer inline-flex items-center rounded-md border border-transparent bg-blue-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
										<svg x-show="<?php echo esc_attr( $store_is_loading ); ?>"
											x-cloak
											class="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
											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>
										<span x-text="<?php echo esc_attr( sprintf(
											"%s ? '%s' : (%s ? %s : '%s')",
											$store_is_loading,
											esc_js( __( 'Closing...', 'rewardswp' ) ),
											$store_is_new_raw,
											$store_add_title,
											esc_js( __( 'Done', 'rewardswp' ) )
										) ); ?>">
											<?php esc_html_e( 'Done', 'rewardswp' ); ?>
										</span>
									</button>
								</div>
							</div>
					</div>
				</div>
			</div>

		<?php
	}

	/**
	 * Get the view contents as a string.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args Arguments for the view.
	 * @return string The view contents.
	 */
	public function get_contents( array $args = [] ): string {
		ob_start();
		$this->render( $args );
		return ob_get_clean();
	}
}
