<?php
namespace R2_Offload\Admin;

use R2_Offload\Migration\Migrator;
use R2_Offload\Migration\Scanner;

defined( 'ABSPATH' ) || exit;

final class Migration_Page {

	private Scanner $scanner;
	private Migrator $migrator;

	public function __construct( Scanner $scanner, Migrator $migrator ) {
		$this->scanner  = $scanner;
		$this->migrator = $migrator;
	}

	public function render(): void {
		$scan     = $this->scanner->get_state();
		$progress = $this->migrator->progress();
		$ctrl     = $progress['control'];
		$failed   = $this->migrator->failed_items( 100 );
		?>
		<div class="wrap" id="r2-offload-migration">
			<h1><?php esc_html_e( 'R2 Offload — Migration', 'r2-offload' ); ?></h1>

			<?php
			$settings     = \R2_Offload\Plugin::instance()->settings;
			$serve_remote = (int) $settings->get( 'rewrite_urls' ) === 1;
			$remote_label = \R2_Offload\Storage\Providers::label( $settings->provider() );
			?>
			<div class="r2-serve-switch">
				<strong><?php esc_html_e( 'Serve media from:', 'r2-offload' ); ?></strong>
				<label class="r2-seg">
					<input type="radio" name="r2-serve-source" value="local" <?php checked( ! $serve_remote ); ?>>
					<span><?php esc_html_e( 'WordPress (local)', 'r2-offload' ); ?></span>
				</label>
				<label class="r2-seg">
					<input type="radio" name="r2-serve-source" value="remote" <?php checked( $serve_remote ); ?>>
					<span><?php echo esc_html( $remote_label ); ?> <?php esc_html_e( '(remote)', 'r2-offload' ); ?></span>
				</label>
				<span class="r2-serve-hint"><?php esc_html_e( 'Applies to offloaded Media Library items, WebP/AVIF sidecars, and extra folders (avatars, etc.).', 'r2-offload' ); ?></span>
			</div>

			<h2><?php esc_html_e( '1) Scan media library', 'r2-offload' ); ?></h2>
			<p><?php esc_html_e( 'Scan builds the queue from Media Library attachments (including WebP/AVIF sidecars) and configured uploads folders such as avatars/. Run dry-run first to estimate size/cost.', 'r2-offload' ); ?></p>
			<div class="r2-stat-grid">
				<div><strong data-r2-stat="scan.scanned"><?php echo esc_html( number_format_i18n( $scan['scanned'] ) ); ?></strong> <span><?php esc_html_e( 'scanned', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="scan.queued"><?php echo esc_html( number_format_i18n( $scan['queued'] ) ); ?></strong> <span><?php esc_html_e( 'queued', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="scan.paths_queued"><?php echo esc_html( number_format_i18n( (int) ( $scan['paths_queued'] ?? 0 ) ) ); ?></strong> <span><?php esc_html_e( 'extra-folder files', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="scan.skipped"><?php echo esc_html( number_format_i18n( $scan['skipped'] ) ); ?></strong> <span><?php esc_html_e( 'skipped', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="scan.bytes_total"><?php echo esc_html( size_format( (int) $scan['bytes_total'], 2 ) ); ?></strong> <span><?php esc_html_e( 'bytes', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="scan.finished"><?php echo esc_html( $scan['finished'] ? __( 'Yes', 'r2-offload' ) : __( 'No', 'r2-offload' ) ); ?></strong> <span><?php esc_html_e( 'finished', 'r2-offload' ); ?></span></div>
			</div>
			<p>
				<button class="button button-primary" data-r2-action="scan-start" data-dry="0"><?php esc_html_e( 'Start scan', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="scan-start" data-dry="1"><?php esc_html_e( 'Start dry-run', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="scan-reset"><?php esc_html_e( 'Reset scan', 'r2-offload' ); ?></button>
			</p>

			<h2><?php esc_html_e( '2) Run migration', 'r2-offload' ); ?></h2>
			<div class="r2-stat-grid">
				<div><strong data-r2-stat="mig.pending"><?php echo esc_html( number_format_i18n( (int) $progress['pending'] ) ); ?></strong> <span><?php esc_html_e( 'pending', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="mig.processing"><?php echo esc_html( number_format_i18n( (int) $progress['processing'] ) ); ?></strong> <span><?php esc_html_e( 'processing', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="mig.offloaded"><?php echo esc_html( number_format_i18n( (int) $progress['offloaded'] ) ); ?></strong> <span><?php esc_html_e( 'offloaded', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="mig.failed"><?php echo esc_html( number_format_i18n( (int) $progress['failed'] ) ); ?></strong> <span><?php esc_html_e( 'failed', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="mig.bytes"><?php echo esc_html( size_format( (int) $progress['bytes']['offloaded'], 2 ) . ' / ' . size_format( (int) $progress['bytes']['total'], 2 ) ); ?></strong> <span><?php esc_html_e( 'bytes offloaded', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="mig.status"><?php echo esc_html( $ctrl['status'] ); ?></strong> <span><?php esc_html_e( 'status', 'r2-offload' ); ?></span></div>
			</div>
			<p>
				<label><?php esc_html_e( 'Batch size', 'r2-offload' ); ?>
					<input type="number" id="r2-batch-size" value="<?php echo esc_attr( $ctrl['batch_size'] ); ?>" min="1" max="500">
				</label>
				<label><?php esc_html_e( 'Concurrency', 'r2-offload' ); ?>
					<input type="number" id="r2-concurrency" value="<?php echo esc_attr( $ctrl['concurrency'] ); ?>" min="1" max="16">
				</label>
			</p>
			<p>
				<button class="button button-primary" data-r2-action="migrate-start"><?php esc_html_e( 'Start', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="migrate-pause"><?php esc_html_e( 'Pause', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="migrate-resume"><?php esc_html_e( 'Resume', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="migrate-stop"><?php esc_html_e( 'Stop', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="migrate-retry"><?php esc_html_e( 'Retry all failed', 'r2-offload' ); ?></button>
			</p>

			<h2><?php esc_html_e( 'Failed items', 'r2-offload' ); ?></h2>
			<table class="widefat striped" id="r2-failed-table">
				<thead><tr>
					<th><?php esc_html_e( 'ID', 'r2-offload' ); ?></th>
					<th><?php esc_html_e( 'Preview', 'r2-offload' ); ?></th>
					<th><?php esc_html_e( 'Attempts', 'r2-offload' ); ?></th>
					<th><?php esc_html_e( 'Error', 'r2-offload' ); ?></th>
					<th><?php esc_html_e( 'Updated', 'r2-offload' ); ?></th>
					<th></th>
				</tr></thead>
				<tbody data-r2-failed-body>
					<?php self::render_failed_rows( $failed ); ?>
				</tbody>
			</table>

			<?php $prune = \R2_Offload\Plugin::instance()->pruner->get_state(); ?>
			<h2><?php esc_html_e( '4) Prune local files', 'r2-offload' ); ?></h2>
			<p><?php esc_html_e( 'Delete local copies of attachments that are verified on remote. Free disk space. Runs in batches with live progress. Restore any attachment by ID if needed.', 'r2-offload' ); ?></p>
			<div class="r2-stat-grid">
				<div><strong data-r2-stat="prune.status"><?php echo esc_html( (string) $prune['status'] ); ?></strong> <span><?php esc_html_e( 'status', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.considered"><?php echo esc_html( number_format_i18n( (int) $prune['considered'] ) ); ?></strong> <span><?php esc_html_e( 'considered', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.total"><?php echo esc_html( number_format_i18n( (int) $prune['total'] ) ); ?></strong> <span><?php esc_html_e( 'total', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.pct"><?php
					$pt = (int) $prune['total'];
					$pc = (int) $prune['considered'];
					echo esc_html( $pt > 0 ? (string) (int) floor( ( $pc / $pt ) * 100 ) . '%' : '0%' );
				?></strong> <span><?php esc_html_e( 'progress', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.pruned"><?php echo esc_html( number_format_i18n( (int) $prune['pruned'] ) ); ?></strong> <span><?php esc_html_e( 'pruned', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.skipped"><?php echo esc_html( number_format_i18n( (int) $prune['skipped'] ) ); ?></strong> <span><?php esc_html_e( 'skipped', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.bytes_freed"><?php echo esc_html( size_format( (int) $prune['bytes_freed'], 2 ) ); ?></strong> <span><?php esc_html_e( 'bytes freed', 'r2-offload' ); ?></span></div>
				<div><strong data-r2-stat="prune.last_error"><?php echo esc_html( (string) ( $prune['last_error'] ?: '—' ) ); ?></strong> <span><?php esc_html_e( 'last error', 'r2-offload' ); ?></span></div>
			</div>
			<p data-r2-stat="prune.message" class="r2-prune-message"><?php echo esc_html( (string) ( $prune['message'] ?: '' ) ); ?></p>
			<p>
				<button class="button" data-r2-action="prune-start" data-dry="1" data-r2-prune-btn><?php esc_html_e( 'Dry-run prune', 'r2-offload' ); ?></button>
				<button class="button button-primary" data-r2-action="prune-start" data-dry="0" data-r2-prune-btn><?php esc_html_e( 'Prune verified local files', 'r2-offload' ); ?></button>
				<button class="button" data-r2-action="prune-stop" data-r2-prune-stop><?php esc_html_e( 'Stop prune', 'r2-offload' ); ?></button>
			</p>
			<pre id="r2-prune-result"><?php
			if ( ! empty( $prune['errors'] ) ) {
				echo esc_html( wp_json_encode( $prune['errors'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) );
			}
			?></pre>
			<p>
				<label><?php esc_html_e( 'Restore attachment ID', 'r2-offload' ); ?>
					<input type="number" id="r2-restore-id" min="1">
				</label>
				<button class="button" data-r2-action="restore"><?php esc_html_e( 'Restore from remote', 'r2-offload' ); ?></button>
			</p>

			<h2><?php esc_html_e( 'Debug', 'r2-offload' ); ?></h2>
			<p>
				<button class="button" data-r2-action="debug-dump"><?php esc_html_e( 'Dump queue state + log tail', 'r2-offload' ); ?></button>
			</p>
			<pre id="r2-debug-result"></pre>

			<h2><?php esc_html_e( '3) Verify', 'r2-offload' ); ?></h2>
			<p>
				<label><?php esc_html_e( 'Attachment ID', 'r2-offload' ); ?>
					<input type="number" id="r2-verify-id" min="1">
				</label>
				<button class="button" data-r2-action="verify-one"><?php esc_html_e( 'Verify attachment', 'r2-offload' ); ?></button>
			</p>
			<pre id="r2-verify-result"></pre>
		</div>
		<?php
	}

	public static function render_failed_rows( array $failed ): void {
		if ( empty( $failed ) ) {
			echo '<tr><td colspan="6">' . esc_html__( 'No failed items.', 'r2-offload' ) . '</td></tr>';
			return;
		}
		foreach ( $failed as $row ) {
			$id   = (int) $row->attachment_id;
			$path = (string) ( $row->relative_path ?? '' );
			if ( $path !== '' ) {
				$label = esc_html( $path );
				$img   = '—';
				$edit  = '';
			} else {
				$label = esc_html( (string) $id );
				$img   = wp_get_attachment_image( $id, [ 60, 60 ], true );
				$edit  = get_edit_post_link( $id );
			}
			echo '<tr>';
			echo '<td>' . $label . ( $edit ? ' <a href="' . esc_url( $edit ) . '" target="_blank">↗</a>' : '' ) . '</td>';
			echo '<td>' . ( $img ?: '—' ) . '</td>';
			echo '<td>' . esc_html( (string) $row->attempts ) . '</td>';
			echo '<td><code style="white-space:pre-wrap;">' . esc_html( (string) $row->last_error ) . '</code></td>';
			echo '<td>' . esc_html( (string) $row->updated_at ) . '</td>';
			echo '<td><button class="button" data-r2-action="retry-one" data-id="' . esc_attr( $id ) . '">' . esc_html__( 'Retry', 'r2-offload' ) . '</button></td>';
			echo '</tr>';
		}
	}
}
