<?php
/**
 * File upload 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\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use function Awesomemotive\Rewardswp\Helpers\kses;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

class FileUploadComponentView extends AbstractView implements ViewInterface {
	/**
	 * Icon helper for rendering SVG icons.
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Constructor.
	 *
	 * @param IconHelper $icon_helper Icon helper instance.
	 */
	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render a reusable file upload component for CSV files.
	 *
	 * @param array $args {
	 *   @type string $label            Field label.
	 *   @type string $help_text        Optional help text below the button.
	 *   @type string $accept           File types to accept (default: .csv).
	 *   @type int    $max_size_mb      Maximum file size in MB (default: 5).
	 *   @type string $button_text      Button text for upload.
	 *   @type string $uploading_text   Text shown while uploading.
	 *   @type string $x_ref            x-ref key for Alpine root reference.
	 *   @type string $on_upload        Alpine expression to call on successful upload.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$args = wp_parse_args(
			$args,
			[
				'label'          => __( 'Upload File', 'rewardswp' ),
				'help_text'      => '',
				'accept'         => '.csv',
				'max_size_mb'    => 5,
				'button_text'    => __( 'Choose File', 'rewardswp' ),
				'uploading_text' => __( 'Uploading...', 'rewardswp' ),
				'x_ref'          => 'fileUpload',
				'on_upload'      => '',
			]
		);

		$max_size_bytes = $args['max_size_mb'] * 1024 * 1024;
		?>

		<div class="space-y-2">
			<?php if ( ! empty( $args['label'] ) ) : ?>
				<label class="block text-sm font-medium text-gray-700 mb-1">
					<?php echo esc_html( $args['label'] ); ?>
				</label>
			<?php endif; ?>

			<div
				x-ref="<?php echo esc_attr( $args['x_ref'] ); ?>"
				x-data="{
					isUploading: false,
					isDragOver: false,
					fileName: '',
					fileSize: 0,
					uploadedFile: null,
					errorMessage: '',

					handleFileSelect(event) {
						const file = event.target.files[0] || event.dataTransfer?.files[0];
						this.processFile(file);
					},

					processFile(file) {
						this.errorMessage = '';
						
						if (!file) {
							return;
						}

						// Validate file type
						if (!file.name.toLowerCase().endsWith('.csv')) {
							this.errorMessage = '<?php echo esc_js( __( 'Please select a CSV file.', 'rewardswp' ) ); ?>';
							return;
						}

						// Validate file size
						if (file.size > <?php echo esc_js( $max_size_bytes ); ?>) {
							this.errorMessage = '<?php echo esc_js( sprintf(
								/* translators: %d: Maximum allowed file size in megabytes. */
								__( 'File size must be less than %d MB.', 'rewardswp' ),
								$args['max_size_mb']
							) ); ?>';
							return;
						}

						this.fileName = file.name;
						this.fileSize = file.size;
						this.uploadedFile = file;

											// Dispatch custom event with file data
					this.$dispatch('file-uploaded', { file: file });
					
					// Call parent callback if provided (fallback)
					<?php if ( ! empty( $args['on_upload'] ) ) : ?>
						<?php echo esc_js( $args['on_upload'] ); ?>;
					<?php endif; ?>
					},

					removeFile() {
						this.fileName = '';
						this.fileSize = 0;
						this.uploadedFile = null;
						this.errorMessage = '';
						this.$refs.fileInput.value = '';
					},

					formatFileSize(bytes) {
						if (bytes === 0) return '0 Bytes';
						const k = 1024;
						const sizes = ['Bytes', 'KB', 'MB', 'GB'];
						const i = Math.floor(Math.log(bytes) / Math.log(k));
						return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
					},

					triggerFileInput() {
						this.$refs.fileInput.click();
					}
				}"
				x-on:remove-file.window="removeFile()"
				class="w-full"
			>
				<!-- Hidden file input -->
				<input
					type="file"
					x-ref="fileInput"
					x-on:change="handleFileSelect($event)"
					accept="<?php echo esc_attr( $args['accept'] ); ?>"
					class="hidden"
				/>

				<!-- Upload area when no file -->
				<div 
					x-show="!uploadedFile"
					x-on:dragover.prevent="isDragOver = true"
					x-on:dragleave.prevent="isDragOver = false"
					x-on:drop.prevent="isDragOver = false; handleFileSelect($event)"
					x-bind:class="{ 'border-blue-500 bg-blue-50': isDragOver }"
					class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors duration-200 cursor-pointer"
					x-on:click="triggerFileInput()"
				>
					<?php echo wp_kses( $this->icon_helper->get_icon( 'file-csv', 'mx-auto h-12 w-12 text-gray-400' ), svg_kses() ); ?>
					<div class="mt-4">
						<p class="text-sm text-gray-600">
							<?php esc_html_e( 'Click to upload or drag and drop', 'rewardswp' ); ?>
						</p>
						<p class="text-xs text-gray-500 mt-1">
							<?php
							echo esc_html(
								sprintf(
									/* translators: %d: Maximum allowed file size in megabytes. */
									__( 'CSV files up to %d MB', 'rewardswp' ),
									$args['max_size_mb']
								)
							);
							?>
						</p>
					</div>
					<div class="mt-4">
						<button type="button" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
							<svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
							</svg>
							<?php echo esc_html( $args['button_text'] ); ?>
						</button>
					</div>
				</div>

				<!-- File preview when uploaded -->
				<div x-show="uploadedFile" class="border border-gray-200 rounded-lg p-4 bg-gray-50">
					<div class="flex items-center justify-between">
						<div class="flex items-center space-x-3">
							<div class="flex-shrink-0">
								<?php echo wp_kses( $this->icon_helper->get_icon( 'file-csv', 'h-8 w-8 text-green-500' ), svg_kses() ); ?>
							</div>
							<div class="min-w-0 flex-1">
								<p class="text-sm font-medium text-gray-900" x-text="fileName"></p>
								<p class="text-xs text-gray-500" x-text="formatFileSize(fileSize)"></p>
							</div>
						</div>
						<div class="flex-shrink-0">
							<button
								type="button"
								x-on:click.stop="removeFile(); $dispatch('reset-import')"
								class="text-sm text-red-600 hover:text-red-800 font-medium"
							>
								<?php esc_html_e( 'Remove', 'rewardswp' ); ?>
							</button>
						</div>
					</div>
				</div>

				<!-- Error message -->
				<div x-show="errorMessage" class="mt-2 p-3 bg-red-50 border border-red-200 rounded-md">
					<div class="flex">
						<div class="flex-shrink-0">
							<svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
								<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 text-red-800" x-text="errorMessage"></p>
						</div>
					</div>
				</div>

				<!-- Help text -->
				<?php if ( ! empty( $args['help_text'] ) ) : ?>
					<div class="mt-2">
						<p class="text-xs text-gray-500"><?php echo wp_kses( $args['help_text'], kses() ); ?></p>
					</div>
				<?php endif; ?>
			</div>
		</div>

		<?php
	}
}
