<?php

namespace ImageSizesPanel;

use WP_PowerSuite\Core\AbstractModule;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Module extends AbstractModule {

	private const MODULE_ID      = 'image-sizes-panel';
	private const MODULE_VERSION = '1.0.0';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Image Sizes Panel', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'See all available image sizes for any image and copy URLs with one click. No more digging through your uploads folder or guessing size dimensions.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return [ 'admin', 'ajax' ];
	}

	protected function registerHooks(): void {
		add_action( 'wp_ajax_wpps_image_sizes_panel_get_sizes', [ $this, 'ajaxGetSizes' ] );
		add_action( 'add_meta_boxes_attachment', [ $this, 'addMetaBox' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueueAssets' ] );
		add_action( 'load-upload.php', [ $this, 'registerUploadPageHooks' ] );
	}

	public function registerUploadPageHooks(): void {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		add_filter( 'media_row_actions', [ $this, 'addRowAction' ], 10, 2 );
	}

	public function addRowAction( array $actions, \WP_Post $post ): array {
		if ( ! current_user_can( 'edit_post', $post->ID ) || ! wp_attachment_is_image( $post->ID ) ) {
			return $actions;
		}

		$actions['wpps_image_sizes'] = sprintf(
			'<a href="#" class="wpps-image-sizes-trigger" data-attachment-id="%d">%s %s</a>',
			(int) $post->ID,
			'📐',
			esc_html__( 'Image Sizes', 'wp-powersuite' )
		);

		return $actions;
	}

	public function addMetaBox(): void {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		$post = get_post();
		if ( ! $post || ! wp_attachment_is_image( $post->ID ) || ! current_user_can( 'edit_post', $post->ID ) ) {
			return;
		}

		add_meta_box(
			'wpps-image-sizes-panel',
			'📐 ' . __( 'Available Image Sizes', 'wp-powersuite' ),
			[ $this, 'renderMetaBox' ],
			'attachment',
			'side'
		);
	}

	public function renderMetaBox( \WP_Post $post ): void {
		$sizes = $this->getSizesForAttachment( $post->ID );
		if ( empty( $sizes ) ) {
			$url = admin_url( 'admin.php?page=powersuite#module-regenerate-thumbnails' );
			echo '<p class="description">' . esc_html__( 'No image sizes available.', 'wp-powersuite' ) . '</p>';
			echo '<p class="description" style="margin-top:8px">' . esc_html__( 'Use Regenerate Thumbnails to create sizes for existing images.', 'wp-powersuite' ) . '</p>';
			echo '<a href="' . esc_url( $url ) . '" class="button button-small" target="_blank" rel="noopener">' . esc_html__( 'Open Regenerate Thumbnails', 'wp-powersuite' ) . '</a>';
			return;
		}
		?>
		<div class="wpps-image-sizes-panel">
			<?php foreach ( $sizes as $size ) : ?>
				<div class="wpps-isp-size-row">
					<div class="wpps-isp-size-header">
						<span class="wpps-isp-size-name"><?php echo esc_html( $size['name'] ); ?></span>
						<span class="wpps-isp-size-dims"><?php echo esc_html( $size['dimensions'] ); ?></span>
					</div>
					<div class="wpps-isp-size-url-row">
						<input type="text" class="wpps-isp-url-input" value="<?php echo esc_attr( $size['url'] ); ?>" readonly />
						<button type="button" class="button button-small wpps-isp-copy-btn" data-url="<?php echo esc_attr( $size['url'] ); ?>" aria-label="<?php esc_attr_e( 'Copy URL', 'wp-powersuite' ); ?>"><?php esc_html_e( 'Copy', 'wp-powersuite' ); ?></button>
					</div>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
	}

	public function ajaxGetSizes(): void {
		if ( ! check_ajax_referer( 'wpps_image_sizes_panel', 'nonce', false ) ) {
			wp_send_json_error( [ 'message' => __( 'Security check failed.', 'wp-powersuite' ) ] );
		}

		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$id = isset( $_POST['attachment_id'] ) ? absint( $_POST['attachment_id'] ) : 0;
		if ( ! $id || get_post_type( $id ) !== 'attachment' ) {
			wp_send_json_error( [ 'message' => __( 'Invalid attachment.', 'wp-powersuite' ) ] );
		}

		if ( ! current_user_can( 'edit_post', $id ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		if ( ! wp_attachment_is_image( $id ) ) {
			wp_send_json_error( [ 'message' => __( 'Not an image.', 'wp-powersuite' ) ] );
		}

		wp_send_json_success( [ 'sizes' => $this->getSizesForAttachment( $id ) ] );
	}

	public function getSizesForAttachment( int $id ): array {
		$out  = [];
		$seen = [];

		foreach ( get_intermediate_image_sizes() as $name ) {
			$src = wp_get_attachment_image_src( $id, $name );
			if ( ! $src || empty( $src[0] ) || isset( $seen[ $src[0] ] ) ) {
				continue;
			}

			$seen[ $src[0] ] = true;
			$w               = (int) ( $src[1] ?? 0 );
			$h               = (int) ( $src[2] ?? 0 );

			$out[] = [
				'name'       => $this->label( $name ),
				'dimensions' => $w && $h ? " ({$w}×{$h})" : '',
				'url'        => esc_url( $src[0] ),
			];
		}

		$full = wp_get_attachment_image_url( $id, 'full' );
		if ( $full && ! isset( $seen[ $full ] ) ) {
			$meta = wp_get_attachment_metadata( $id );
			$w    = (int) ( $meta['width'] ?? 0 );
			$h    = (int) ( $meta['height'] ?? 0 );

			$out[] = [
				'name'       => $this->label( 'full' ),
				'dimensions' => $w && $h ? " ({$w}×{$h})" : '',
				'url'        => esc_url( $full ),
			];
		}

		return $out;
	}

	private function label( string $name ): string {
		$map = [
			'thumbnail'    => __( 'Thumbnail', 'wp-powersuite' ),
			'medium'       => __( 'Medium', 'wp-powersuite' ),
			'medium_large' => __( 'Medium Large', 'wp-powersuite' ),
			'large'        => __( 'Large', 'wp-powersuite' ),
			'full'         => __( 'Full', 'wp-powersuite' ),
		];

		return $map[ $name ] ?? ucwords( str_replace( [ '-', '_' ], ' ', $name ) );
	}

	public function enqueueAssets(): void {
		if ( ! current_user_can( 'upload_files' ) ) {
			return;
		}

		global $pagenow;

		if ( $pagenow === 'post.php' && ! empty( $_GET['post'] ) ) {
			$post_id = absint( $_GET['post'] );
			if ( get_post_type( $post_id ) === 'attachment' && current_user_can( 'edit_post', $post_id ) ) {
				$this->enqueueMetaBoxAssets();
			}
			return;
		}

		if ( $pagenow === 'upload.php' && $this->isMediaListMode() ) {
			$this->enqueueListAssets();
		}
	}

	private function enqueueMetaBoxAssets(): void {
		$base = WP_POWERSUITE_PLUGIN_URL . 'modules/' . self::MODULE_ID . '/assets/';
		wp_enqueue_style( 'wpps-image-sizes-panel', $base . 'image-sizes-panel.css', [], self::MODULE_VERSION );
		wp_enqueue_script( 'wpps-image-sizes-panel', $base . 'image-sizes-panel.js', [], self::MODULE_VERSION, true );
		wp_localize_script(
			'wpps-image-sizes-panel',
			'wppsImageSizesPanel',
			[
				'copied' => __( 'Copied!', 'wp-powersuite' ),
			]
		);
	}

	private function enqueueListAssets(): void {
		$base = WP_POWERSUITE_PLUGIN_URL . 'modules/' . self::MODULE_ID . '/assets/';
		wp_enqueue_style( 'wpps-image-sizes-panel', $base . 'image-sizes-panel.css', [], self::MODULE_VERSION );
		wp_enqueue_script( 'wpps-image-sizes-panel-list', $base . 'image-sizes-panel-list.js', [], self::MODULE_VERSION, true );
		wp_localize_script(
			'wpps-image-sizes-panel-list',
			'wppsImageSizesPanelList',
			[
				'ajax'  => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'wpps_image_sizes_panel' ),
				'regen' => admin_url( 'admin.php?page=powersuite#module-regenerate-thumbnails' ),
				'i18n'  => [
					'copy'   => __( 'Copy', 'wp-powersuite' ),
					'copied' => __( 'Copied!', 'wp-powersuite' ),
					'load'   => __( 'Loading sizes…', 'wp-powersuite' ),
					'none'   => __( 'No image sizes available.', 'wp-powersuite' ),
					'hint'   => __( 'Use Regenerate Thumbnails to create sizes for existing images.', 'wp-powersuite' ),
					'open'   => __( 'Open Regenerate Thumbnails', 'wp-powersuite' ),
					'err'    => __( 'Could not load image sizes.', 'wp-powersuite' ),
					'title'  => __( 'Available Image Sizes', 'wp-powersuite' ),
				],
			]
		);
	}

	private function isMediaListMode(): bool {
		$mode = ( isset( $_GET['mode'] ) && in_array( $_GET['mode'], [ 'grid', 'list' ], true ) )
			? sanitize_key( wp_unslash( (string) $_GET['mode'] ) )
			: ( get_user_option( 'media_library_mode', get_current_user_id() ) ?: 'grid' );

		return $mode === 'list';
	}
}
