<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

use APD\Portability\ProductPackageImporter;
use APD\Repositories\ProductConfigRepository;
use APD\Support\RequestData;

defined('ABSPATH') || exit;

class ToolsPage
{
    public function render() : void
    {
        $sampleUrl = ASUKA_PRODUCT_DESIGNER_URL . 'docs/SAMPLE_PRODUCT_CONFIG.json';
        $settings = (new AdminSettings())->all();
        $configs = (new ProductConfigRepository())->allForSelect();
        $query = RequestData::query();
        $notice = sanitize_key((string) ($query['apd_notice'] ?? ''));
        $packageToken = sanitize_key((string) ($query['package_token'] ?? ''));
        $preview = $packageToken !== '' ? (new ProductPackageImporter())->previewToken($packageToken) : null;
        $runtimeError = get_transient('apd_tools_error_' . get_current_user_id());
        delete_transient('apd_tools_error_' . get_current_user_id());
        $importResult = get_transient('apd_package_result_' . get_current_user_id());
        delete_transient('apd_package_result_' . get_current_user_id());
        if (is_wp_error($preview)) {
            $runtimeError = $preview->get_error_message();
            $preview = null;
            $packageToken = '';
        }
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($settings['admin_theme']); ?>">
            <div class="apd-page-heading">
                <div>
                    <span class="apd-badge"><?php esc_html_e('Portability', 'asuka-product-designer'); ?></span>
                    <h1><?php esc_html_e('Import / Export', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Move complete Asuka Designer products between WordPress, Shopify, standalone JavaScript integrations, and future host platforms.', 'asuka-product-designer'); ?></p>
                </div>
            </div>

            <?php $this->renderNotice($notice, is_string($runtimeError) ? $runtimeError : '', is_array($importResult) ? $importResult : []); ?>

            <section class="apd-card apd-portability-intro">
                <div class="apd-card-head">
                    <div>
                        <span class="apd-badge apd-badge-live"><?php esc_html_e('Portable format', 'asuka-product-designer'); ?></span>
                        <h2><?php esc_html_e('One product, every Asuka integration', 'asuka-product-designer'); ?></h2>
                    </div>
                    <span class="apd-package-extension">.asuka.zip</span>
                </div>
                <p><?php esc_html_e('The package contains only reusable designer data: views, objects, 2D/3D state, elements, layout, modules, fonts, colors, pricing rules, themes, templates, and local media.', 'asuka-product-designer'); ?></p>
                <p class="description"><?php esc_html_e('Store products, SKUs, catalog bindings, carts, orders, customers, and licenses are never included. Each platform links the imported custom product to its own catalog separately.', 'asuka-product-designer'); ?></p>
            </section>

            <div class="apd-grid apd-grid-2 apd-portability-grid">
                <?php $this->renderPackageExport($configs); ?>
                <?php $this->renderPackageImport($configs, $packageToken, is_array($preview) ? $preview : null); ?>
            </div>

            <details class="apd-card apd-portability-legacy">
                <summary>
                    <span>
                        <strong><?php esc_html_e('Legacy config JSON', 'asuka-product-designer'); ?></strong>
                        <small><?php esc_html_e('WordPress-only compatibility tools', 'asuka-product-designer'); ?></small>
                    </span>
                    <span class="apd-badge"><?php esc_html_e('Advanced', 'asuka-product-designer'); ?></span>
                </summary>
                <div class="apd-grid apd-grid-2 apd-portability-legacy-content">
                    <?php $this->renderLegacyImport($configs); ?>
                    <?php $this->renderLegacyExport($configs, $sampleUrl); ?>
                </div>
            </details>
        </div>
        <?php
    }

    private function renderPackageExport(array $configs) : void
    {
        ?>
        <section class="apd-card">
            <div class="apd-card-head">
                <div>
                    <span class="apd-badge"><?php esc_html_e('Export', 'asuka-product-designer'); ?></span>
                    <h2><?php esc_html_e('Create a portable product', 'asuka-product-designer'); ?></h2>
                </div>
            </div>
            <p><?php esc_html_e('Build a self-contained package that can be versioned, backed up, or imported by another Asuka Designer integration.', 'asuka-product-designer'); ?></p>
            <form class="apd-tool-form" method="get" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('apd_export_product_package'); ?>
                <input type="hidden" name="action" value="apd_export_product_package">
                <label class="apd-field apd-field-stacked">
                    <span><?php esc_html_e('Custom product', 'asuka-product-designer'); ?></span>
                    <select name="config_id" required <?php disabled($configs === []); ?>>
                        <option value=""><?php esc_html_e('Select a custom product...', 'asuka-product-designer'); ?></option>
                        <?php foreach ($configs as $config) : ?>
                            <option value="<?php echo esc_attr((string) $config['id']); ?>"><?php echo esc_html($config['title']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <fieldset class="apd-package-options">
                    <legend><?php esc_html_e('Package contents', 'asuka-product-designer'); ?></legend>
                    <?php $this->checkbox('include_assets', __('Local media and 3D files', 'asuka-product-designer'), __('Images, fonts, textures, GLB/glTF files, and their local dependencies.', 'asuka-product-designer')); ?>
                    <?php $this->checkbox('include_template', __('Assigned reusable template', 'asuka-product-designer'), __('Adds the template used to compose the designer interface.', 'asuka-product-designer')); ?>
                    <?php $this->checkbox('include_themes', __('Assigned reusable themes', 'asuka-product-designer'), __('Adds every reusable theme referenced by the product or its template.', 'asuka-product-designer')); ?>
                </fieldset>
                <div class="apd-inline-actions">
                    <button type="submit" class="button button-primary button-hero" <?php disabled($configs === []); ?>><?php esc_html_e('Download portable package', 'asuka-product-designer'); ?></button>
                </div>
            </form>
        </section>
        <?php
    }

    private function renderPackageImport(array $configs, string $token, ?array $preview) : void
    {
        ?>
        <section class="apd-card">
            <div class="apd-card-head">
                <div>
                    <span class="apd-badge"><?php esc_html_e('Import', 'asuka-product-designer'); ?></span>
                    <h2><?php echo $preview ? esc_html__('Review the package', 'asuka-product-designer') : esc_html__('Import a portable product', 'asuka-product-designer'); ?></h2>
                </div>
            </div>
            <?php if ($preview === null) : ?>
                <p><?php esc_html_e('Analyze a package first. Nothing is written to WordPress until you confirm the review.', 'asuka-product-designer'); ?></p>
                <form class="apd-tool-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data">
                    <?php wp_nonce_field('apd_inspect_product_package'); ?>
                    <input type="hidden" name="action" value="apd_inspect_product_package">
                    <label class="apd-field apd-field-stacked apd-package-drop-field">
                        <span><?php esc_html_e('Asuka product package', 'asuka-product-designer'); ?></span>
                        <input type="file" name="apd_product_package" accept=".zip,.asuka.zip,application/zip" required>
                        <small><?php esc_html_e('Checksums, paths, file types, and package size are verified before the review opens.', 'asuka-product-designer'); ?></small>
                    </label>
                    <div class="apd-inline-actions">
                        <button type="submit" class="button button-primary button-hero"><?php esc_html_e('Analyze package', 'asuka-product-designer'); ?></button>
                    </div>
                </form>
            <?php else : ?>
                <?php $this->renderPreview($preview); ?>
                <form class="apd-tool-form apd-package-confirm" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <?php wp_nonce_field('apd_import_product_package'); ?>
                    <input type="hidden" name="action" value="apd_import_product_package">
                    <input type="hidden" name="package_token" value="<?php echo esc_attr($token); ?>">
                    <label class="apd-field apd-field-stacked">
                        <span><?php esc_html_e('Import destination', 'asuka-product-designer'); ?></span>
                        <select name="existing_config_id">
                            <option value="0"><?php esc_html_e('Create a new custom product', 'asuka-product-designer'); ?></option>
                            <?php foreach ($configs as $config) : ?>
                                <option value="<?php echo esc_attr((string) $config['id']); ?>"><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('Replace: %s', 'asuka-product-designer'), $config['title'])); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label class="apd-field apd-field-stacked">
                        <span><?php esc_html_e('Template and theme conflicts', 'asuka-product-designer'); ?></span>
                        <select name="dependency_policy">
                            <option value="copy"><?php esc_html_e('Create safe copies', 'asuka-product-designer'); ?></option>
                            <option value="reuse"><?php esc_html_e('Reuse items with the same slug', 'asuka-product-designer'); ?></option>
                            <option value="replace"><?php esc_html_e('Replace items with the same slug', 'asuka-product-designer'); ?></option>
                        </select>
                    </label>
                    <label class="apd-toggle">
                        <input type="checkbox" name="open_after_import" value="1" checked>
                        <span><?php esc_html_e('Open the imported custom product after import', 'asuka-product-designer'); ?></span>
                    </label>
                    <div class="apd-inline-actions">
                        <button type="submit" class="button button-primary button-hero"><?php esc_html_e('Import portable product', 'asuka-product-designer'); ?></button>
                    </div>
                </form>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-package-discard">
                    <?php wp_nonce_field('apd_discard_product_package'); ?>
                    <input type="hidden" name="action" value="apd_discard_product_package">
                    <input type="hidden" name="package_token" value="<?php echo esc_attr($token); ?>">
                    <button type="submit" class="button button-link"><?php esc_html_e('Cancel this import', 'asuka-product-designer'); ?></button>
                </form>
            <?php endif; ?>
        </section>
        <?php
    }

    private function renderPreview(array $preview) : void
    {
        $themes = (array) ($preview['themes'] ?? []);
        ?>
        <div class="apd-package-preview">
            <div class="apd-package-preview-title">
                <strong><?php echo esc_html((string) $preview['title']); ?></strong>
                <span><?php echo esc_html((string) $preview['slug']); ?></span>
            </div>
            <dl class="apd-package-facts">
                <div><dt><?php esc_html_e('Media', 'asuka-product-designer'); ?></dt><dd><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('%1$d files, %2$s', 'asuka-product-designer'), (int) $preview['assets'], size_format((int) $preview['assetBytes']))); ?></dd></div>
                <div><dt><?php esc_html_e('Template', 'asuka-product-designer'); ?></dt><dd><?php echo esc_html((string) ($preview['template'] ?: __('None', 'asuka-product-designer'))); ?></dd></div>
                <div><dt><?php esc_html_e('Themes', 'asuka-product-designer'); ?></dt><dd><?php echo esc_html($themes !== [] ? implode(', ', $themes) : __('None', 'asuka-product-designer')); ?></dd></div>
                <div><dt><?php esc_html_e('Designer', 'asuka-product-designer'); ?></dt><dd><?php echo esc_html((string) ($preview['designerVersion'] ?: __('Unknown', 'asuka-product-designer'))); ?></dd></div>
            </dl>
            <?php if (! empty($preview['externalHosts'])) : ?>
                <p class="apd-package-warning"><?php echo esc_html(sprintf(/* translators: Placeholder values are populated from the current administration record. */ __('External files remain linked to: %s', 'asuka-product-designer'), implode(', ', (array) $preview['externalHosts']))); ?></p>
            <?php endif; ?>
            <?php if (! empty($preview['existingProductId'])) : ?>
                <p class="apd-package-warning"><?php esc_html_e('A custom product with the same slug already exists. Create a copy or explicitly select a product to replace.', 'asuka-product-designer'); ?></p>
            <?php endif; ?>
        </div>
        <?php
    }

    private function renderLegacyImport(array $configs) : void
    {
        ?>
        <div class="apd-portability-legacy-pane">
            <h3><?php esc_html_e('Import WordPress config JSON', 'asuka-product-designer'); ?></h3>
            <p><?php esc_html_e('Use this only for older WordPress backups. It is not portable to Shopify or standalone integrations.', 'asuka-product-designer'); ?></p>
            <form class="apd-tool-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" enctype="multipart/form-data">
                <?php wp_nonce_field('apd_import_config'); ?>
                <input type="hidden" name="action" value="apd_import_config">
                <label class="apd-field apd-field-stacked"><span><?php esc_html_e('Config JSON file', 'asuka-product-designer'); ?></span><input type="file" name="apd_config_file" accept="application/json,.json" required></label>
                <label class="apd-field apd-field-stacked"><span><?php esc_html_e('Replace existing config (optional)', 'asuka-product-designer'); ?></span><select name="apd_existing_config_id"><option value="0"><?php esc_html_e('Create a new config', 'asuka-product-designer'); ?></option><?php foreach ($configs as $config) : ?><option value="<?php echo esc_attr((string) $config['id']); ?>"><?php echo esc_html($config['title']); ?></option><?php endforeach; ?></select></label>
                <label class="apd-toggle"><input type="checkbox" name="apd_open_after_import" value="1" checked><span><?php esc_html_e('Open after import', 'asuka-product-designer'); ?></span></label>
                <button type="submit" class="button button-secondary"><?php esc_html_e('Import legacy JSON', 'asuka-product-designer'); ?></button>
            </form>
        </div>
        <?php
    }

    private function renderLegacyExport(array $configs, string $sampleUrl) : void
    {
        ?>
        <div class="apd-portability-legacy-pane">
            <h3><?php esc_html_e('Export WordPress config JSON', 'asuka-product-designer'); ?></h3>
            <p><?php esc_html_e('Download the raw WordPress config without media or reusable dependencies.', 'asuka-product-designer'); ?></p>
            <form class="apd-tool-form" method="get" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <?php wp_nonce_field('apd_export_config'); ?>
                <input type="hidden" name="action" value="apd_export_config">
                <label class="apd-field apd-field-stacked"><span><?php esc_html_e('Choose a config', 'asuka-product-designer'); ?></span><select name="config_id" required><option value=""><?php esc_html_e('Select a config...', 'asuka-product-designer'); ?></option><?php foreach ($configs as $config) : ?><option value="<?php echo esc_attr((string) $config['id']); ?>"><?php echo esc_html($config['title']); ?></option><?php endforeach; ?></select></label>
                <div class="apd-inline-actions"><button type="submit" class="button button-secondary"><?php esc_html_e('Export legacy JSON', 'asuka-product-designer'); ?></button><a class="button button-link" href="<?php echo esc_url($sampleUrl); ?>" target="_blank" rel="noreferrer"><?php esc_html_e('Open sample', 'asuka-product-designer'); ?></a></div>
            </form>
        </div>
        <?php
    }

    private function checkbox(string $name, string $label, string $description) : void
    {
        ?>
        <label class="apd-package-option">
            <input type="checkbox" name="<?php echo esc_attr($name); ?>" value="1" checked>
            <span><strong><?php echo esc_html($label); ?></strong><small><?php echo esc_html($description); ?></small></span>
        </label>
        <?php
    }

    private function renderNotice(string $notice, string $runtimeError, array $result) : void
    {
        if ($runtimeError !== '') {
            echo '<div class="notice notice-error is-dismissible"><p>' . esc_html($runtimeError) . '</p></div>';
            return;
        }
        if ($notice === 'package_imported') {
            $message = sprintf(
                /* translators: Placeholder values are populated from the current administration record. */ __('Portable product imported. %1$d media files were added and %2$d media references were resolved.', 'asuka-product-designer'),
                (int) ($result['assetsImported'] ?? 0),
                (int) ($result['assetsResolved'] ?? 0)
            );
            $query = RequestData::query();
            $configId = absint($query['imported_config_id'] ?? 0);
            $link = $configId > 0 ? ' <a href="' . esc_url(get_edit_post_link($configId, '')) . '">' . esc_html__('Open the product', 'asuka-product-designer') . '</a>' : '';
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($message) . wp_kses_post($link) . '</p></div>';
            return;
        }

        $messages = [
            'imported' => __('Config imported successfully.', 'asuka-product-designer'),
            'import_missing' => __('Please choose a JSON file to import.', 'asuka-product-designer'),
            'import_invalid' => __('This file is not a valid APD config package.', 'asuka-product-designer'),
            'import_failed' => __('The config could not be imported.', 'asuka-product-designer'),
            'export_failed' => __('The selected config could not be exported.', 'asuka-product-designer'),
            'package_export_failed' => __('The portable package could not be exported.', 'asuka-product-designer'),
            'package_inspect_failed' => __('The portable package could not be analyzed.', 'asuka-product-designer'),
            'package_import_failed' => __('The portable package could not be imported.', 'asuka-product-designer'),
        ];
        if (! isset($messages[$notice])) {
            return;
        }
        $class = $notice === 'imported' ? 'notice-success' : 'notice-error';
        echo '<div class="notice ' . esc_attr($class) . ' is-dismissible"><p>' . esc_html($messages[$notice]) . '</p></div>';
    }
}
