<?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\Support\QADiagnostics;
use APD\Support\RequestData;

defined('ABSPATH') || exit;

class QADiagnosticsPage
{
    public function render() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'asuka-product-designer'));
        }

        $service = new QADiagnostics();
        $results = $service->getResults();
        $summary = $service->buildSummary($results);
        $diagnostics = $service->buildDiagnostics();
        $statuses = $service->getStatusOptions();
        $groups = $service->getScenarioGroups();
        $settings = (new AdminSettings())->all();
        $query = RequestData::query();
        ?>
        <div class="wrap apd-admin-shell apd-admin-theme-<?php echo esc_attr($settings['admin_theme']); ?> apd-qa-page">
            <div class="apd-page-heading apd-page-heading-wide">
                <div>
                    <span class="apd-badge"><?php esc_html_e('Quality control', 'asuka-product-designer'); ?></span>
                    <h1><?php esc_html_e('QA & Diagnostics', 'asuka-product-designer'); ?></h1>
                    <p><?php esc_html_e('Run your regression checklist, keep diagnostics visible, and save validation notes for the current build in one consistent workspace.', 'asuka-product-designer'); ?></p>
                </div>
                <div class="apd-inline-actions apd-inline-actions-wrap apd-qa-toolbar-actions">
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                        <?php wp_nonce_field('apd_export_qa_report'); ?>
                        <input type="hidden" name="action" value="apd_export_qa_report">
                        <button type="submit" class="button button-secondary"><?php esc_html_e('Export QA report (JSON)', 'asuka-product-designer'); ?></button>
                    </form>
                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" onsubmit="return confirm('<?php echo esc_js(__('Reset all checklist results for this site?', 'asuka-product-designer')); ?>');">
                        <?php wp_nonce_field('apd_reset_qa_report'); ?>
                        <input type="hidden" name="action" value="apd_reset_qa_report">
                        <button type="submit" class="button button-secondary apd-button-danger"><?php esc_html_e('Reset checklist', 'asuka-product-designer'); ?></button>
                    </form>
                </div>
            </div>

            <?php if (isset($query['apd_qa_saved'])) : ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('QA checklist saved.', 'asuka-product-designer'); ?></p></div>
            <?php endif; ?>
            <?php if (isset($query['apd_qa_reset'])) : ?>
                <div class="notice notice-warning is-dismissible"><p><?php esc_html_e('QA checklist reset.', 'asuka-product-designer'); ?></p></div>
            <?php endif; ?>

            <section class="apd-card apd-qa-summary-shell">
                <div class="apd-card-head apd-card-head-stack">
                    <div>
                        <h2><?php esc_html_e('Snapshot', 'asuka-product-designer'); ?></h2>
                        <p><?php esc_html_e('Track overall coverage before validating admin, frontend, pricing, translations, and vendor synchronization changes.', 'asuka-product-designer'); ?></p>
                    </div>
                </div>
                <div class="apd-qa-summary-cards">
                    <?php $this->renderSummaryCard(__('Scenarios', 'asuka-product-designer'), (string) $summary['total'], 'neutral'); ?>
                    <?php $this->renderSummaryCard(__('Passed', 'asuka-product-designer'), (string) $summary['passed'], 'passed'); ?>
                    <?php $this->renderSummaryCard(__('Failed', 'asuka-product-designer'), (string) $summary['failed'], 'failed'); ?>
                    <?php $this->renderSummaryCard(__('Blocked', 'asuka-product-designer'), (string) $summary['blocked'], 'blocked'); ?>
                    <?php $this->renderSummaryCard(__('Not tested', 'asuka-product-designer'), (string) $summary['not_tested'], 'neutral'); ?>
                </div>
            </section>

            <section class="apd-card apd-qa-diagnostics-shell">
                <div class="apd-card-head apd-card-head-stack">
                    <div>
                        <h2><?php esc_html_e('Environment diagnostics', 'asuka-product-designer'); ?></h2>
                        <p><?php esc_html_e('Keep the current plugin build, WooCommerce status, assets, and runtime assumptions visible while you review each scenario.', 'asuka-product-designer'); ?></p>
                    </div>
                </div>
                <div class="apd-qa-diagnostic-grid">
                    <?php foreach ($diagnostics as $panel) : ?>
                        <section class="apd-qa-panel<?php echo isset($panel['summary']) ? ' apd-qa-panel--summary' : ''; ?><?php echo isset($panel['status']) ? ' apd-qa-panel--' . esc_attr((string) $panel['status']) : ''; ?>">
                            <div class="apd-qa-panel__heading">
                                <h2><?php echo esc_html((string) ($panel['label'] ?? '')); ?></h2>
                                <?php if (isset($panel['summary'])) : ?>
                                    <span class="apd-readiness-pill is-<?php echo esc_attr((string) ($panel['status'] ?? 'warning')); ?>">
                                        <?php echo esc_html((string) $panel['summary']); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <dl class="apd-qa-dl">
                                <?php foreach ((array) ($panel['items'] ?? []) as $item) : ?>
                                    <div>
                                        <dt>
                                            <?php if (isset($item['status'])) : ?>
                                                <span class="apd-readiness-dot is-<?php echo esc_attr((string) $item['status']); ?>" aria-hidden="true"></span>
                                            <?php endif; ?>
                                            <?php echo esc_html((string) ($item['label'] ?? '')); ?>
                                        </dt>
                                        <dd><?php echo esc_html((string) ($item['value'] ?? '—')); ?></dd>
                                    </div>
                                <?php endforeach; ?>
                            </dl>
                        </section>
                    <?php endforeach; ?>
                </div>
            </section>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="apd-qa-form-shell">
                <?php wp_nonce_field('apd_save_qa_report'); ?>
                <input type="hidden" name="action" value="apd_save_qa_report">

                <section class="apd-card apd-qa-checklist-shell">
                    <div class="apd-card-head apd-card-head-stack">
                        <div>
                            <h2><?php esc_html_e('Regression checklist', 'asuka-product-designer'); ?></h2>
                            <p><?php esc_html_e('Review every scenario, update its status, and store implementation notes directly with the checklist.', 'asuka-product-designer'); ?></p>
                        </div>
                        <div class="apd-inline-actions apd-inline-actions-wrap">
                            <button type="submit" class="button button-primary button-hero"><?php esc_html_e('Save QA checklist', 'asuka-product-designer'); ?></button>
                        </div>
                    </div>

                    <div class="apd-qa-checklist-list">
                        <?php foreach ($groups as $group) : ?>
                            <section class="apd-qa-checklist-group apd-section-card">
                                <div class="apd-section-card__head">
                                    <h3><?php echo esc_html((string) ($group['label'] ?? '')); ?></h3>
                                </div>
                                <div class="apd-table-wrap">
                                    <table class="widefat striped apd-qa-table">
                                        <thead>
                                            <tr>
                                                <th><?php esc_html_e('Scenario', 'asuka-product-designer'); ?></th>
                                                <th class="apd-col-status"><?php esc_html_e('Status', 'asuka-product-designer'); ?></th>
                                                <th><?php esc_html_e('Notes', 'asuka-product-designer'); ?></th>
                                                <th class="apd-col-updated"><?php esc_html_e('Last update', 'asuka-product-designer'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ((array) ($group['items'] ?? []) as $item) : ?>
                                                <?php
                                                $id = sanitize_key((string) ($item['id'] ?? ''));
                                                $entry = $results[$id] ?? ['status' => 'not_tested', 'notes' => '', 'updatedAt' => ''];
                                                ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo esc_html((string) ($item['label'] ?? $id)); ?></strong>
                                                    </td>
                                                    <td>
                                                        <select name="apd_qa_results[<?php echo esc_attr($id); ?>][status]" class="regular-text">
                                                            <?php foreach ($statuses as $statusKey => $statusLabel) : ?>
                                                                <option value="<?php echo esc_attr($statusKey); ?>" <?php selected((string) ($entry['status'] ?? 'not_tested'), $statusKey); ?>><?php echo esc_html($statusLabel); ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <textarea name="apd_qa_results[<?php echo esc_attr($id); ?>][notes]" rows="2" class="large-text"><?php echo esc_textarea((string) ($entry['notes'] ?? '')); ?></textarea>
                                                    </td>
                                                    <td>
                                                        <?php echo esc_html((string) ($entry['updatedAt'] ?? '—') ?: '—'); ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </section>
                        <?php endforeach; ?>
                    </div>

                    <div class="apd-inline-actions apd-inline-actions-wrap apd-qa-footer-actions">
                        <button type="submit" class="button button-primary button-hero"><?php esc_html_e('Save QA checklist', 'asuka-product-designer'); ?></button>
                    </div>
                </section>
            </form>
        </div>
        <?php
    }

    public function save() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'asuka-product-designer'));
        }

        check_admin_referer('apd_save_qa_report');
        $post = RequestData::post();
        $results = is_array($post['apd_qa_results'] ?? null) ? $post['apd_qa_results'] : [];
        (new QADiagnostics())->saveResults($results);

        wp_safe_redirect(add_query_arg([
            'page' => 'apd-qa-diagnostics',
            'apd_qa_saved' => 1,
        ], admin_url('admin.php')));
        exit;
    }

    public function reset() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'asuka-product-designer'));
        }

        check_admin_referer('apd_reset_qa_report');
        (new QADiagnostics())->resetResults();

        wp_safe_redirect(add_query_arg([
            'page' => 'apd-qa-diagnostics',
            'apd_qa_reset' => 1,
        ], admin_url('admin.php')));
        exit;
    }

    public function export() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You do not have permission to perform this action.', 'asuka-product-designer'));
        }

        check_admin_referer('apd_export_qa_report');

        $service = new QADiagnostics();
        $payload = [
            'exportedAt' => current_time('mysql'),
            'pluginVersion' => defined('ASUKA_PRODUCT_DESIGNER_VERSION') ? ASUKA_PRODUCT_DESIGNER_VERSION : '',
            'summary' => $service->buildSummary(),
            'diagnostics' => $service->buildDiagnostics(),
            'results' => $service->getResults(),
            'scenarioGroups' => $service->getScenarioGroups(),
        ];

        nocache_headers();
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename=apd-qa-report-' . gmdate('Ymd-His') . '.json');
        echo wp_json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    protected function renderSummaryCard(string $label, string $value, string $tone = 'neutral') : void
    {
        ?>
        <div class="apd-qa-card apd-qa-card--<?php echo esc_attr($tone); ?>">
            <span class="apd-qa-card__label"><?php echo esc_html($label); ?></span>
            <strong class="apd-qa-card__value"><?php echo esc_html($value); ?></strong>
        </div>
        <?php
    }
}
