<?php
/**
 * Member detail 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\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Models\Member;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use function Awesomemotive\Rewardswp\Helpers\get_view_component; // If you have a toggle component
use function Awesomemotive\Rewardswp\Helpers\format_currency;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

class MemberDetailModalView extends AbstractView implements ViewInterface {

	/**
	 * Icon helper instance.
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     Required. An array of arguments.
	 *
	 *     @type Member $member The Member object.
	 *     @type array  $member_modal_data Pre-fetched/formatted data for modal display, including:
	 *         @type string $country_display Formatted country.
	 *         @type string $first_seen_display Formatted date.
	 *         @type string $referral_link_display Member's referral link/code.
	 *         @type string $referred_by_display Who referred this member.
	 *         @type string $member_type_html HTML for the member type badge.
	 *         @type bool   $program_participation_status Current participation status.
	 *         @type array  $referral_summary_stats {
	 *              @type int $traffic
	 *              @type int $completed_referrals
	 *              @type string $conversion_rate_display
	 *              @type string $referral_revenue_display
	 *              @type string $last_referral_date_display
	 *         }
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		if ( ! isset( $args['member'] ) || ! $args['member'] instanceof Member ) {
			// Or render a specific error message within the modal structure
			echo 'Error: Member data not provided.'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			return;
		}

		/**
		 * Member instance.
		 *
		 * @var Member $member
		 */
		$member     = $args['member'];
		$modal_data = wp_parse_args(
			$args['member_modal_data'] ?? [],
			[
				'country_display'              => esc_html__( 'N/A', 'rewardswp' ),
				'first_seen_display'           => esc_html__( 'N/A', 'rewardswp' ),
				'referral_link_display'        => esc_html( $member->referral_code ?: __( 'N/A', 'rewardswp' ) ),
				'referred_by_display'          => esc_html__( '-', 'rewardswp' ),
				'gravatar_url_large'           => '', // Will be populated by controller
				'member_type_html'             => sprintf( '<span class="inline-flex items-center rounded-md bg-gray-50 px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10">%s</span>', esc_html( $member->status ) ), // Basic fallback
				'program_participation_status' => true, // Default to true for display
				'referral_summary_stats'       => [
					'traffic'                    => 0,
					'completed_referrals'        => 0,
					'conversion_rate_display'    => '0%',
					'referral_revenue_display'   => format_currency( 0 ),
					'last_referral_date_display' => esc_html__( '-', 'rewardswp' ),
				],
				'modal_action_nonce'           => '', // Default empty, should be provided by controller
			]
		);

		// Unique ID for Alpine.js x-data context if needed for multiple modals on a page
		$modal_id = 'member-detail-modal-' . $member->id;

		// For the toggle - assuming you have a ToggleComponentView available via DI or get_view_component
		// This is a simplified representation. You'd pass the correct name, section, etc.
		// For now, just a placeholder structure.
		$toggle_args = [
			'name'         => 'member_participation_status[' . $member->id . ']',
			'is_checked'   => $modal_data['program_participation_status'],
			'label'        => esc_html__( 'Program Participation', 'rewardswp' ),
			// 'on_click'   => 'handleToggleSave(' . $member->id . ', toggleEnabled)', // JS function to handle AJAX save
			'button_align' => 'right',
		];

		?>
		<div
			x-data="memberDetailModal(<?php echo esc_js( $member->id ); ?>, '<?php echo esc_js( $member->referral_code ); ?>', <?php echo wp_json_encode( (bool) $modal_data['program_participation_status'] ); ?>, '<?php echo esc_js( $modal_data['modal_action_nonce'] ); ?>')"
			{{-- Remove fixed positioning from this root, as parent container in ListTable handles it --}}
			{{-- class="fixed inset-0 z-[99999] bg-opacity-50 transition-opacity flex items-center justify-center p-4" --}}
			class="transition-opacity w-full h-full flex items-center justify-center p-4" {{-- Ensure it fills its parent which is fixed --}}
			aria-labelledby="modal-title-<?php echo esc_attr( $member->id ); ?>"
			x-on:keydown.escape.window="$dispatch('close-member-modal')"
		>
			<?php // Backdrop like in RewardsModalView - make it fixed to cover the viewport (parent is already fixed) ?>
			<div
				class="fixed inset-0 transition-opacity -z-10" {{-- Lower z-index than panel, but will be contained by ultimate parent's z-index --}}
				aria-hidden="true"
				x-on:click="$dispatch('close-member-modal')"
			>
				<div class="absolute inset-0 bg-slate-900/40"></div>
			</div>

			<?php // Modal Panel - relative to the flex container to be centered ?>
			<div class="relative bg-white rounded-lg shadow-xl transform transition-all sm:my-8 sm:max-w-3xl w-full overflow-y-auto max-h-[90vh]">
				<?php // Modal Header ?>
				<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:items-center sm:justify-between border-b border-gray-200">
					<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title-<?php echo esc_attr( $member->id ); ?>">
						<?php esc_html_e( 'Member:', 'rewardswp' ); ?> (<?php echo esc_html( $member->email ); ?>)
					</h3>
					<div class="mt-3 sm:mt-0 sm:ml-4 flex items-center">
						<?php // "Delete Customer" link removed from here ?>
						<button
							type="button"
							class="text-gray-400 hover:text-gray-500 focus:outline-none"
							x-on:click="$dispatch('close-member-modal')"
							aria-label="<?php esc_attr_e( 'Close', 'rewardswp' ); ?>"
						>
							<span class="sr-only"><?php esc_html_e( 'Close', 'rewardswp' ); ?></span>
							<?php /* Changed icon to 'modal-close' for consistency */ ?>
							<?php echo wp_kses($this->icon_helper->get_icon( 'modal-close' ), svg_kses() ); ?>
						</button>
					</div>
				</div>

				<?php // Modal Body ?>
				<div class="px-4 pt-5 pb-4 sm:p-6">
					<?php // Member Information Section ?>
					<div class="flex items-start gap-4 mb-6 pb-6 border-b border-gray-200">
						<?php if ( ! empty( $modal_data['gravatar_url_large'] ) ) : ?>
						<img src="<?php echo esc_url( $modal_data['gravatar_url_large'] ); ?>" alt="<?php echo esc_attr( $member->get_full_name() ); ?>" class="h-20 w-20 rounded-full bg-gray-200">
						<?php else : ?>
						<div class="h-20 w-20 rounded-full bg-gray-200 flex items-center justify-center text-gray-400">
							<?php echo wp_kses( $this->icon_helper->get_icon( 'user', 'h-10 w-10' ), svg_kses() ); // Fallback icon. ?>
						</div>
						<?php endif; ?>
						<div class="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-4 gap-x-6 gap-y-4 flex-1">
							<div>
								<dt class="text-sm font-medium text-gray-500"><?php esc_html_e( 'First Seen', 'rewardswp' ); ?></dt>
								<dd class="mt-1 text-sm text-gray-900"><?php echo esc_html( $modal_data['first_seen_display'] ); ?></dd>
							</div>
							<div>
								<dt class="text-sm font-medium text-gray-500"><?php esc_html_e( 'Referral Link', 'rewardswp' ); ?></dt>
								<dd class="mt-1 text-sm text-gray-900"><?php echo esc_html( $modal_data['referral_link_display'] ); ?></dd>
							</div>
							<div>
								<dt class="text-sm font-medium text-gray-500"><?php esc_html_e( 'Referred By', 'rewardswp' ); ?></dt>
								<dd class="mt-1 text-sm text-gray-900"><?php echo esc_html( $modal_data['referred_by_display'] ); ?></dd>
							</div>
							<div>
								<dt class="text-sm font-medium text-gray-500"><?php esc_html_e( 'Type', 'rewardswp' ); ?></dt>
								<dd class="mt-1 text-sm text-gray-900"><?php echo wp_kses_post( $modal_data['member_type_html'] ); // Expecting HTML for badge ?></dd>
							</div>
						</div>
					</div>

					<?php // Program Participation Toggle ?>
					<div class="bg-blue-50 p-4 rounded-lg flex items-center justify-between mb-6">
						<p class="text-sm text-blue-700"><?php esc_html_e( 'This member can participate in your program.', 'rewardswp' ); ?></p>
						<?php
							// This is where you would render your ToggleComponentView
							// For now, a simplified Alpine-controlled toggle:
						?>
						<button
							type="button"
							x-on:click="programParticipation = !programParticipation; onToggleParticipation()"
							x-bind:class="{ 'bg-blue-600': programParticipation, 'bg-gray-200': !programParticipation }"
							class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
							role="switch"
							x-bind:aria-checked="programParticipation.toString()"
						>
							<span class="sr-only"><?php esc_html_e( 'Participate in program', 'rewardswp' ); ?></span>
							<span
								x-bind:class="{ 'translate-x-5': programParticipation, 'translate-x-0': !programParticipation }"
								class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200"
							></span>
						</button>
					</div>

					<?php // Tabbed Content Area ?>
					<div class="border-b border-gray-200">
						<nav class="-mb-px flex space-x-8" aria-label="<?php esc_attr_e( 'Tabs', 'rewardswp' ); ?>">
							<a href="#" x-on:click.prevent="activeTab = 'referral'" x-bind:class="{'border-blue-500 text-blue-600': activeTab === 'referral', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'referral'}" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
								<?php echo $this->icon_helper->get_icon( 'referral', 'h-5 w-5 mr-2 inline-block' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php esc_html_e( 'Referral', 'rewardswp' ); ?>
							</a>
							<a href="#" x-on:click.prevent="activeTab = 'points'" x-bind:class="{'border-blue-500 text-blue-600': activeTab === 'points', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'points'}" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
								<?php echo $this->icon_helper->get_icon( 'points', 'h-5 w-5 mr-2 inline-block' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php esc_html_e( 'Points', 'rewardswp' ); ?>
							</a>
							<a href="#" x-on:click.prevent="activeTab = 'rewards'" x-bind:class="{'border-blue-500 text-blue-600': activeTab === 'rewards', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300': activeTab !== 'rewards'}" class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
								<?php echo $this->icon_helper->get_icon( 'rewards', 'h-5 w-5 mr-2 inline-block' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php esc_html_e( 'Rewards', 'rewardswp' ); ?>
							</a>
						</nav>
					</div>

					<div class="mt-6">
						<?php // Referral Tab Content ?>
						<div x-show="activeTab === 'referral'" x-cloak>
							<div class="bg-gray-50 p-4 rounded-lg grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4 mb-6">
								<div>
									<dt class="text-xs font-medium text-gray-500"><?php esc_html_e( 'Referral traffic', 'rewardswp' ); ?></dt>
									<dd class="mt-1 text-xl font-semibold text-gray-900"><?php echo esc_html( $modal_data['referral_summary_stats']['traffic'] ); ?></dd>
								</div>
								<div>
									<dt class="text-xs font-medium text-gray-500"><?php esc_html_e( 'Completed referrals', 'rewardswp' ); ?></dt>
									<dd class="mt-1 text-xl font-semibold text-gray-900"><?php echo esc_html( $modal_data['referral_summary_stats']['completed_referrals'] ); ?></dd>
								</div>
								<div>
									<dt class="text-xs font-medium text-gray-500"><?php esc_html_e( 'Conversion rate', 'rewardswp' ); ?></dt>
									<dd class="mt-1 text-xl font-semibold text-gray-900"><?php echo esc_html( $modal_data['referral_summary_stats']['conversion_rate_display'] ); ?></dd>
								</div>
								<div>
									<dt class="text-xs font-medium text-gray-500"><?php esc_html_e( 'Referral revenue', 'rewardswp' ); ?></dt>
									<dd class="mt-1 text-xl font-semibold text-gray-900"><?php echo esc_html( $modal_data['referral_summary_stats']['referral_revenue_display'] ); ?></dd>
								</div>
								<div>
									<dt class="text-xs font-medium text-gray-500"><?php esc_html_e( 'Last referral date', 'rewardswp' ); ?></dt>
									<dd class="mt-1 text-xl font-semibold text-gray-900"><?php echo esc_html( $modal_data['referral_summary_stats']['last_referral_date_display'] ); ?></dd>
								</div>
							</div>

							<h4 class="text-md font-medium text-gray-700 mb-2"><?php esc_html_e( 'Referrals Activity', 'rewardswp' ); ?></h4>
							<div class="text-center py-8 border border-dashed border-gray-300 rounded-lg">
								<p class="text-sm text-gray-500"><?php esc_html_e( 'No referral activity for this customer.', 'rewardswp' ); ?></p>
								<?php // Placeholder for actual referrals list/table ?>
							</div>

							<div class="mt-6 pt-6 border-t border-gray-200">
								<label for="referral_code_<?php echo esc_attr( $member->id ); ?>" class="block text-md font-medium text-gray-700 mb-1"><?php esc_html_e( 'Change Referral Code', 'rewardswp' ); ?></label>
								<div class="flex items-center">
									<input
										type="text"
										name="referral_code_<?php echo esc_attr( $member->id ); ?>"
										id="referral_code_<?php echo esc_attr( $member->id ); ?>"
										x-model="currentReferralCode"
										class="block w-full rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500 sm:text-sm py-2 px-3"
										x-on:input="referralCodeError = ''" {{-- Clear error on input --}}
									>
									<button
										type="button"
										x-on:click="currentReferralCode = originalReferralCode; referralCodeError = ''"
										class="ml-2 p-2 text-gray-400 hover:text-gray-600 focus:outline-none"
										title="<?php esc_attr_e( 'Revert to original code', 'rewardswp' ); ?>"
										x-show="currentReferralCode !== originalReferralCode"
										x-cloak
									>
										<?php echo wp_kses( $this->icon_helper->get_icon( 'arrow-uturn-left', 'h-5 w-5' ), svg_kses() ); ?>
									</button>
								</div>
								<p x-show="referralCodeError" x-text="referralCodeError" class="mt-2 text-sm text-red-600" x-cloak></p>
							</div>
						</div>

						<?php // Points Tab Content ?>
						<div x-show="activeTab === 'points'" x-cloak>
							<p class="text-gray-500"><?php esc_html_e( 'Points information and history will be displayed here.', 'rewardswp' ); ?></p>
						</div>

						<?php // Rewards Tab Content ?>
						<div x-show="activeTab === 'rewards'" x-cloak>
							<p class="text-gray-500"><?php esc_html_e( 'Rewards information and history will be displayed here.', 'rewardswp' ); ?></p>
						</div>
					</div>
				</div>

				<?php // Modal Footer ?>
				<div class="bg-gray-50 px-4 py-3 sm:px-6 border-t border-gray-200">
					<div x-show="!showDeleteConfirmation" class="sm:flex sm:items-center sm:justify-between">
						<?php // Delete Member link on the left ?>
						<button
							type="button"
							x-on:click="initiateDelete()"
							class="text-sm font-medium text-red-600 hover:text-red-700 focus:outline-none cursor-pointer"
						>
							<?php esc_html_e( 'Delete Member', 'rewardswp' ); ?>
						</button>

						<?php // Save and Close button on the right ?>
						<button
							type="button"
							x-on:click="saveAndCloseHandler()"
							x-bind:disabled="isSaving"
							class="w-full mt-3 sm:mt-0 inline-flex justify-center 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"
						>
							<span x-show="!isSaving" x-cloak><?php esc_html_e( 'Save and Close', 'rewardswp' ); ?></span>
							<span x-show="isSaving" class="flex items-center" x-cloak>
								<svg class="animate-spin -ml-1 mr-3 h-5 w-5 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>
								<?php esc_html_e( 'Saving...', 'rewardswp' ); ?>
							</span>
						</button>
					</div>

					<?php // Delete Confirmation UI ?>
					<div x-show="showDeleteConfirmation" x-cloak class="space-y-4">
						<p class="text-sm text-gray-700">
							<?php esc_html_e( 'To confirm deletion, please type the member\'s referral code below and click "Confirm Deletion". This action cannot be undone.', 'rewardswp' ); ?>
						</p>
						<p class="text-sm font-medium text-gray-900">
							<?php esc_html_e( 'Referral Code to match:', 'rewardswp' ); ?>
							<strong x-text="originalReferralCode || '<?php esc_attr_e( 'N/A', 'rewardswp' ); ?>'"></strong>
						</p>
						<div>
							<label for="delete_confirm_referral_code_<?php echo esc_attr( $member->id ); ?>" class="sr-only"><?php esc_html_e( 'Confirm Referral Code', 'rewardswp' ); ?></label>
							<input
								type="text"
								id="delete_confirm_referral_code_<?php echo esc_attr( $member->id ); ?>"
								x-model="deleteConfirmReferralCodeInput"
								class="block w-full rounded-md border-gray-300 bg-white focus:border-red-500 focus:ring-red-500 sm:text-sm py-2 px-3"
								placeholder="<?php esc_attr_e( 'Type referral code here', 'rewardswp' ); ?>"
								x-on:input="deleteError = ''"
								x-ref="deleteConfirmInput"
							>
						</div>
						<p x-show="deleteError" x-text="deleteError" class="text-sm text-red-600" x-cloak></p>
						<div class="flex justify-end space-x-3">
							<button
								type="button"
								x-on:click="cancelDelete()"
								x-bind:disabled="isDeleting"
								class="rounded-md border border-gray-300 bg-white py-2 px-4 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
							>
								<?php esc_html_e( 'Cancel', 'rewardswp' ); ?>
							</button>
							<button
								type="button"
								x-on:click="confirmDeleteHandler()"
								x-bind:disabled="isDeleting || deleteConfirmReferralCodeInput !== originalReferralCode"
								class="inline-flex justify-center rounded-md border border-transparent bg-red-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50"
							>
								<span x-show="!isDeleting"><?php esc_html_e( 'Confirm Deletion', 'rewardswp' ); ?></span>
								<span x-show="isDeleting" class="flex items-center">
									<svg class="animate-spin -ml-1 mr-3 h-5 w-5 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>
									<?php esc_html_e( 'Deleting...', 'rewardswp' ); ?>
								</span>
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}
