<?php

namespace SugarCalendarBookings\Admin\Settings;

use SugarCalendarBookings\Migration\MigrationIssuesStorage;
use SugarCalendarBookings\Migration\MigrationRegistry;
use SugarCalendarBookings\Options;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Admin\AbstractTabPage;
use SugarCalendarBookings\Support\Helpers\UI;

/**
 * Import/Export Settings tab.
 *
 * @since 1.3.0
 */
class ImportExportSettingsTab extends AbstractTabPage {

	/**
	 * Check if the tab should be loaded.
	 *
	 * Only load if at least one migration source is available.
	 *
	 * @since 1.3.0
	 *
	 * @return bool True if at least one migration source is available, false otherwise.
	 */
	public static function should_load() {

		return ! empty( Plugin::get( MigrationRegistry::class )->get_available_ui_configs() );
	}

	/**
	 * Page title.
	 *
	 * @since 1.3.0
	 *
	 * @return string
	 */
	public static function get_title() {

		return esc_html__( 'Import/Export', 'sugar-calendar-bookings-scheduling-appointments-lite' );
	}

	/**
	 * Page slug.
	 *
	 * @since 1.3.0
	 *
	 * @return string
	 */
	public static function get_slug() {

		return 'settings';
	}

	/**
	 * Page view slug.
	 *
	 * @since 1.3.0
	 *
	 * @return string
	 */
	public static function get_view_slug() {

		return 'import-export';
	}

	/**
	 * Priority in menu position.
	 *
	 * @since 1.3.0
	 *
	 * @return int
	 */
	public static function get_priority() {

		return 50;
	}

	/**
	 * Display page.
	 *
	 * @since 1.3.0
	 */
	public function display_content() {

		$options           = Plugin::get( Options::class );
		$available_configs = Plugin::get( MigrationRegistry::class )->get_available_ui_configs();

		// Import/Export Card Container.
		?>
		<div class="sugar-calendar-bookings-import-export-card">
			<?php foreach ( $available_configs as $source_id => $config ) : ?>
				<?php $this->render_migration_section( $source_id, $config, $options ); ?>
			<?php endforeach; ?>
		</div>
		<?php
		UI::migration_modal_shell();
		UI::confirmation_modal();
	}

	/**
	 * Render a migration section for a specific source.
	 *
	 * @since 1.3.0
	 *
	 * @param string $source_id Source adapter ID.
	 * @param object $config    UI config instance.
	 * @param object $options   Options instance.
	 */
	private function render_migration_section( string $source_id, $config, $options ): void {

		$migration_data   = $options->get( "import.{$source_id}_last_migrated" );
		$has_migrated     = $this->has_migration_data( $migration_data );
		$migration_status = $this->get_migration_status( $migration_data );
		$has_issues       = $migration_status !== 'success' && MigrationIssuesStorage::has_stored_for_source( $source_id );

		?>
		<div class="sugar-calendar-bookings-import-export-item">
			<div class="sugar-calendar-bookings-import-export-content">
				<h3 class="sugar-calendar-bookings-import-export-title">
					<?php
					printf(
						/* translators: %1$s - source name (e.g., "Amelia"). */
						esc_html__( 'Migrate from %1$s', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						esc_html( $config->get_source_name() )
					);
					?>
				</h3>
				<p class="sugar-calendar-bookings-import-export-description">
					<?php
					printf(
						/* translators: %1$s - source name (e.g., "Amelia"). */
						esc_html__( 'Directly import all data from %1$s in one click!', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						esc_html( $config->get_source_name() )
					);
					?>
				</p>
				<?php if ( $has_migrated ) : ?>
					<?php $this->render_migration_status( $migration_data, $migration_status, $options ); ?>
				<?php endif; ?>
			</div>
			<div class="sugar-calendar-bookings-import-export-actions">
				<?php if ( $has_issues ) : ?>
					<button
						type="button"
						class="sugar-calendar-bookings-btn-tertiary sugar-calendar-bookings-btn-sm sugar-calendar-bookings-migration-download-report-btn"
						data-source="<?php echo esc_attr( $source_id ); ?>"
					>
						<?php UI::svg_icon( 'download' ); ?>
						<?php esc_html_e( 'Download Report', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
					</button>
				<?php endif; ?>
				<button
					type="button"
					class="sugar-calendar-bookings-btn-tertiary sugar-calendar-bookings-btn-sm sugar-calendar-bookings-migrate-btn"
					data-source="<?php echo esc_attr( $source_id ); ?>"
				>
					<?php UI::svg_icon( 'file-import' ); ?>
					<?php
					if ( $has_migrated ) {
						esc_html_e( 'Re-Migrate', 'sugar-calendar-bookings-scheduling-appointments-lite' );
					} else {
						esc_html_e( 'Migrate', 'sugar-calendar-bookings-scheduling-appointments-lite' );
					}
					?>
				</button>
			</div>
		</div>
		<?php
	}

	/**
	 * Check if migration data exists.
	 *
	 * Handles both old format (string timestamp) and new format (array).
	 *
	 * @since 1.3.0
	 *
	 * @param mixed $migration_data Migration data from options.
	 *
	 * @return bool
	 */
	private function has_migration_data( $migration_data ): bool {

		if ( empty( $migration_data ) ) {
			return false;
		}

		// Old format: string timestamp.
		if ( is_string( $migration_data ) ) {
			return true;
		}

		// New format: array with date.
		return is_array( $migration_data ) && ! empty( $migration_data['date'] );
	}

	/**
	 * Get migration status from data.
	 *
	 * @since 1.3.0
	 *
	 * @param mixed $migration_data Migration data from options.
	 *
	 * @return string 'success', 'warning', or 'failed'.
	 */
	private function get_migration_status( $migration_data ): string {

		// Old format defaults to success.
		if ( is_string( $migration_data ) ) {
			return 'success';
		}

		return $migration_data['status'] ?? 'success';
	}

	/**
	 * Render migration status indicator.
	 *
	 * @since 1.3.0
	 *
	 * @param mixed   $migration_data Migration data.
	 * @param string  $status         Migration status.
	 * @param Options $options        Options instance.
	 */
	private function render_migration_status( $migration_data, $status, $options ): void {

		$icon_map = [
			'success' => 'check-circle',
			'warning' => 'exclamation-circle-warning',
			'failed'  => 'times-circle',
		];

		$label_map = [
			/* translators: %1$s - migration date. */
			'success' => __( 'Successfully Migrated on %1$s', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			/* translators: %1$s - migration date. */
			'warning' => __( 'Partially Migrated on %1$s', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			/* translators: %1$s - migration date. */
			'failed'  => __( 'Failed Migration on %1$s', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
		];

		$icon  = $icon_map[ $status ] ?? 'check-circle';
		$label = $label_map[ $status ] ?? $label_map['success'];
		$date  = is_array( $migration_data ) ? $migration_data['date'] : $migration_data;

		// Check if this is a failed migration with zero stats (no data to show in modal).
		$is_empty_failed = $status === 'failed' && $this->has_zero_stats( $migration_data );

		?>
		<div class="sugar-calendar-bookings-migration-status sugar-calendar-bookings-migration-status--<?php echo esc_attr( $status ); ?>">
			<button
				type="button"
				class="sugar-calendar-bookings-migration-status-btn"
				id="sugar-calendar-bookings-migration-status-btn"
				<?php echo $is_empty_failed ? 'disabled' : ''; ?>
			>
				<?php UI::svg_icon( $icon ); ?>
				<?php
				echo esc_html(
					sprintf(
						$label,
						wp_date( $options->get( 'display.date_format' ), strtotime( $date ) )
					)
				);
				?>
			</button>
		</div>
		<?php
	}

	/**
	 * Check if migration data has zero stats.
	 *
	 * @since 1.3.0
	 *
	 * @param mixed $migration_data Migration data from options.
	 *
	 * @return bool True if all stats are zero or missing.
	 */
	private function has_zero_stats( $migration_data ): bool {

		if ( ! is_array( $migration_data ) || empty( $migration_data['stats'] ) ) {
			return true;
		}

		$stats = $migration_data['stats'];

		return empty( $stats['total_migrated'] )
			&& empty( $stats['total_skipped'] )
			&& empty( $stats['total_failed'] );
	}


	/**
	 * Get script data for the page.
	 *
	 * @since 1.3.0
	 *
	 * @return array
	 */
	public function get_script_data() {

		$options           = Plugin::get( Options::class );
		$available_configs = Plugin::get( MigrationRegistry::class )->get_available_ui_configs();

		// Build migration configs for each available source.
		$migration_configs = [];
		$migration_data    = [];

		foreach ( $available_configs as $source_id => $config ) {
			$migration_configs[ $source_id ] = $config->get_modal_config();

			$source_migration_data        = $options->get( "import.{$source_id}_last_migrated" );
			$migration_data[ $source_id ] = $this->prepare_migration_data_for_js( $source_migration_data, $options );
		}

		return [
			'ajax_url'          => admin_url( 'admin-ajax.php' ),
			'nonce'             => wp_create_nonce( 'sugar_calendar_bookings' ),
			'migration_configs' => $migration_configs,
			'migration_data'    => $migration_data,
		];
	}

	/**
	 * Prepare migration data for JavaScript.
	 *
	 * @since 1.3.0
	 *
	 * @param mixed   $migration_data Migration data from options.
	 * @param Options $options        Options instance.
	 *
	 * @return array|null Migration data for JS or null if no data.
	 */
	private function prepare_migration_data_for_js( $migration_data, Options $options ): ?array { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		if ( empty( $migration_data ) ) {
			return null;
		}

		// Handle old format (string timestamp).
		if ( is_string( $migration_data ) ) {
			return [
				'date'           => wp_date( $options->get( 'display.date_format' ), strtotime( $migration_data ) ),
				'status'         => 'success',
				'scb_version'    => null,
				'amelia_version' => null,
				'stats'          => null,
				'entities'       => null,
			];
		}

		// New format (array).
		$date = $migration_data['date'] ?? '';

		return [
			'date'           => $date ? wp_date( $options->get( 'display.date_format' ), strtotime( $date ) ) : '',
			'status'         => $migration_data['status'] ?? 'success',
			'scb_version'    => $migration_data['scb_version'] ?? null,
			'amelia_version' => $migration_data['amelia_version'] ?? null,
			'stats'          => $migration_data['stats'] ?? null,
			'entities'       => $migration_data['entities'] ?? null,
		];
	}
}
