<?php

namespace ShopyPress\Views\Admin\Settings;

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

use ShopyPress\Views\Admin\Settings\BaseView;
use ShopyPress\Views\Admin\Settings\IView;
use ShopyPress\Models\SyncState;
use ShopyPress\Utils\OptionUtils;

class ProductSync extends BaseView implements IView
{

    public function render(): void
    {
        $state = SyncState::load();
        $selected_collections = OptionUtils::getInstance()->getOption('selected_collections', []);
        $syncWarningClass = !empty($selected_collections) ? 'd-none' : '';
?>
        <div class="row">
            <div class="col-md-12">
                <h5 class="mb-3"><?php esc_html_e('Product Sync', 'synckube-products-sync-for-shopify'); ?></h5>

                <div class="alert alert-warning product-sync-warning <?php echo esc_attr($syncWarningClass) ?>" role="alert">
                    <strong><?php esc_html_e('Warning:', 'synckube-products-sync-for-shopify'); ?></strong>
                    <?php esc_html_e('Please select at least one collection in the Collections tab before syncing products.', 'synckube-products-sync-for-shopify'); ?>
                </div>

                <!-- Sync Status Card -->
                <div class="card mb-3">
                    <div class="card-body">
                        <h6><?php esc_html_e('Sync Status', 'synckube-products-sync-for-shopify'); ?></h6>
                        <div id="sync-status-container">
                            <?php $this->renderSyncStatus($state); ?>
                        </div>
                    </div>
                </div>

                <!-- Progress Bar -->
                <?php if ($state && $state->isWorking()): ?>
                    <div class="mb-3">
                        <div class="progress" style="height: 30px;">
                            <div id="sync-progress-bar"
                                class="progress-bar progress-bar-striped progress-bar-animated"
                                role="progressbar"
                                style="width: <?php echo esc_attr($state->getProgressPercentage()); ?>%"
                                aria-valuenow="<?php echo esc_attr($state->getProgressPercentage()); ?>"
                                aria-valuemin="0"
                                aria-valuemax="100">
                                <span id="sync-progress-text"><?php echo esc_html(round($state->getProgressPercentage())); ?>%</span>
                            </div>
                        </div>
                        <p class="text-muted mt-2">
                            <span id="sync-progress-details">
                                <?php
                                echo sprintf(
                                    /* translators: %1$d: number of products synced, %2$d: total number of products */
                                    esc_html__('%1$d of %2$d products synced', 'synckube-products-sync-for-shopify'),
                                    esc_html($state->total_processed),
                                    esc_html($state->total_products)
                                );
                                ?>
                            </span>
                        </p>
                    </div>
                <?php endif; ?>

                <!-- Action Buttons -->
                <div class="mb-3">
                    <button id="btn-start-sync"
                        class="btn btn-primary"
                        <?php disabled($state && $state->isWorking()); ?>>
                        <span class="dashicons dashicons-update"></span>
                        <?php esc_html_e('Start Sync', 'synckube-products-sync-for-shopify'); ?>
                    </button>
                    <button id="btn-reset-sync" class="btn btn-warning">
                        <span class="dashicons dashicons-undo"></span>
                        <?php esc_html_e('Reset Sync', 'synckube-products-sync-for-shopify'); ?>
                    </button>
                </div>

                <!-- Error Messages -->
                <?php if ($state && $state->hasError()): ?>
                    <div class="alert alert-danger" role="alert">
                        <h6><?php esc_html_e('Errors:', 'synckube-products-sync-for-shopify'); ?></h6>
                        <ul class="mb-0">
                            <?php foreach ($state->errors as $error): ?>
                                <li>
                                    <?php echo esc_html($error['message']); ?>
                                    <small class="text-muted">
                                        - <?php echo esc_html(wp_date('Y-m-d H:i:s', $error['timestamp'])); ?>
                                    </small>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <!-- Last Sync Info -->
                <?php if ($state && $state->isCompleted()): ?>
                    <div class="alert alert-success" role="alert">
                        <?php
                        echo sprintf(
                            /* translators: %s: timestamp of the last completed sync */
                            esc_html__('Last sync completed: %s', 'synckube-products-sync-for-shopify'),
                            esc_html(wp_date('Y-m-d H:i:s', $state->updated_at))
                        );
                        ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
<?php
    }

    private function renderSyncStatus(?SyncState $state): void
    {
        if (!$state) {
            echo '<span class="badge bg-secondary">' . esc_html__('Not started', 'synckube-products-sync-for-shopify') . '</span>';
            return;
        }

        if ($state->isWorking()) {
            echo '<span class="badge bg-primary">' . esc_html__('Working', 'synckube-products-sync-for-shopify') . '</span>';
            echo ' <small class="text-muted">' . esc_html__('Phase:', 'synckube-products-sync-for-shopify') . ' ' . esc_html($state->phase) . '</small>';
        } elseif ($state->isCompleted()) {
            echo '<span class="badge bg-success">' . esc_html__('Completed', 'synckube-products-sync-for-shopify') . '</span>';
        } elseif ($state->hasError()) {
            echo '<span class="badge bg-danger">' . esc_html__('Error', 'synckube-products-sync-for-shopify') . '</span>';
        }
    }
}
