<?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\WooCommerce;

use APD\Support\ProductionPackBuilder;
use APD\Support\RequestData;
use WC_Order;
use WC_Order_Item_Product;

defined('ABSPATH') || exit;

class AdminOrderMetaBox
{
    public function register() : void
    {
        add_filter('woocommerce_hidden_order_itemmeta', [$this, 'hideRawItemMeta']);
        add_action('add_meta_boxes', [$this, 'addMetaBoxes']);
        add_action('add_meta_boxes_woocommerce_page_wc-orders', [$this, 'addMetaBoxes']);
        add_action('woocommerce_after_order_itemmeta', [$this, 'renderInlineItemSummary'], 10, 3);
    }

    public function hideRawItemMeta(array $hidden) : array
    {
        $keys = [
            '_apd_config_id',
            '_apd_config_title',
            '_apd_product_id',
            '_apd_product_title',
            '_apd_product_sku',
            '_apd_variation_id',
            '_apd_variation_label',
            '_apd_variation_attributes',
            '_apd_user_design_id',
            '_apd_design_json',
            '_apd_state_json',
            '_apd_design_summary',
            '_apd_preview_url',
            '_apd_resume_url',
            '_apd_payload_version',
            '_apd_pricing_payload',
            '_apd_price_base',
            '_apd_price_adjustment',
            '_apd_price_total',
            '_apd_price_breakdown',
            '_apd_production_status',
            '_apd_production_notes',
            '_apd_production_data',
        ];

        foreach ($keys as $key) {
            if (! in_array($key, $hidden, true)) {
                $hidden[] = $key;
            }
        }

        return $hidden;
    }

    public function addMetaBoxes() : void
    {
        $screens = ['shop_order'];
        if (function_exists('wc_get_page_screen_id')) {
            $screens[] = wc_get_page_screen_id('shop-order');
        } else {
            $screens[] = 'woocommerce_page_wc-orders';
        }

        foreach (array_unique(array_filter($screens, 'is_string')) as $screen) {
            add_meta_box(
                'apd-order-summary',
                __('Asuka Designer', 'asuka-product-designer'),
                [$this, 'renderMetaBox'],
                $screen,
                'normal',
                'default'
            );
        }
    }

    public function renderMetaBox(mixed $postOrOrderObject) : void
    {
        $order = $this->resolveOrder($postOrOrderObject);
        if (! $order) {
            echo '<p>' . esc_html__('Unable to load this order.', 'asuka-product-designer') . '</p>';
            return;
        }

        $builder = new ProductionPackBuilder();
        $items = [];
        foreach ($order->get_items('line_item') as $item) {
            if (! $item instanceof WC_Order_Item_Product) {
                continue;
            }
            $pack = $builder->build($item, $order);
            if (! empty($pack['isCustomized'])) {
                $items[] = $pack;
            }
        }

        if ($items === []) {
            echo '<p>' . esc_html__('No Asuka Designer data was attached to this order.', 'asuka-product-designer') . '</p>';
            return;
        }

        echo '<div class="apd-order-summary">';
        foreach ($items as $pack) {
            $configLabel = (int) ($pack['configId'] ?? 0) > 0 ? $this->renderPostReference((int) $pack['configId']) : '<span class="apd-order-empty">' . esc_html__('N/A', 'asuka-product-designer') . '</span>';
            $sourceProductId = absint($pack['variationId'] ?? 0) ?: absint($pack['productId'] ?? 0);
            $sourceProductLabel = $sourceProductId > 0 ? $this->renderPostReference($sourceProductId) : '<span class="apd-order-empty">' . esc_html__('N/A', 'asuka-product-designer') . '</span>';
            $userDesignLabel = (int) ($pack['userDesignId'] ?? 0) > 0 ? $this->renderPostReference((int) $pack['userDesignId']) : '<span class="apd-order-empty">' . esc_html__('Not saved', 'asuka-product-designer') . '</span>';
            $previewHtml = ! empty($pack['previewUrl'])
                ? '<img src="' . esc_url((string) $pack['previewUrl']) . '" alt="' . esc_attr__('Design preview', 'asuka-product-designer') . '">'
                : '<span class="apd-order-empty">' . esc_html__('No preview captured.', 'asuka-product-designer') . '</span>';
            $detailUrl = add_query_arg([
                'page' => 'apd-production',
                'order_id' => (int) $pack['orderId'],
                'item_id' => (int) $pack['itemId'],
            ], admin_url('admin.php'));
            $statusClass = 'apd-order-pill apd-order-pill--' . esc_attr((string) ($pack['productionStatus'] ?? 'pending'));
            $server = RequestData::server();
            $requestUri = esc_url_raw((string) ($server['REQUEST_URI'] ?? ''));
            $redirectUrl = $requestUri !== '' ? admin_url(ltrim($requestUri, '/')) : $detailUrl;

            echo '<section class="apd-order-card">';
            echo '<div class="apd-order-card__head">';
            echo '<div>';
            echo '<h3 class="apd-order-card__title">' . esc_html((string) $pack['itemName']) . '</h3>';
            echo '<div class="apd-order-card__meta">';
            printf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Line item #%1$d · Qty %2$d · Order #%3$d', 'asuka-product-designer'), (int) $pack['itemId'], (int) $pack['quantity'], (int) $pack['orderId']);
            echo '</div>';
            echo '</div>';
            echo '<span class="' . esc_attr($statusClass) . '">' . esc_html((string) ($pack['productionStatusLabel'] ?? __('To produce', 'asuka-product-designer'))) . '</span>';
            echo '</div>';

            echo '<div class="apd-order-card__body">';
            echo '<div>';
            echo '<dl class="apd-order-dl">';
            echo '<dt>' . esc_html__('Custom Product', 'asuka-product-designer') . '</dt><dd>' . wp_kses_post($configLabel) . '</dd>';
            echo '<dt>' . esc_html__('Woo source product', 'asuka-product-designer') . '</dt><dd>' . wp_kses_post($sourceProductLabel) . '</dd>';
            echo '<dt>' . esc_html__('Saved user design', 'asuka-product-designer') . '</dt><dd>' . wp_kses_post($userDesignLabel) . '</dd>';
            if (! empty($pack['resumeUrl'])) {
                echo '<dt>' . esc_html__('Resume link', 'asuka-product-designer') . '</dt><dd><a href="' . esc_url((string) $pack['resumeUrl']) . '">' . esc_html__('Open saved customization', 'asuka-product-designer') . '</a></dd>';
            }
            echo '<dt>' . esc_html__('Production page', 'asuka-product-designer') . '</dt><dd><a href="' . esc_url($detailUrl) . '">' . esc_html__('Open production pack', 'asuka-product-designer') . '</a></dd>';
            echo '</dl>';

            echo '<div class="apd-order-pricing">';
            echo '<div class="apd-order-pricing__grid">';
            echo '<div><strong>' . esc_html__('Base price', 'asuka-product-designer') . '</strong><br>' . wp_kses_post(wc_price((float) ($pack['price']['base'] ?? 0))) . '</div>';
            echo '<div><strong>' . esc_html__('Customization adjustment', 'asuka-product-designer') . '</strong><br>' . wp_kses_post(wc_price((float) ($pack['price']['adjustment'] ?? 0))) . '</div>';
            echo '<div><strong>' . esc_html__('Final unit price', 'asuka-product-designer') . '</strong><br>' . wp_kses_post(wc_price((float) ($pack['price']['total'] ?? 0))) . '</div>';
            echo '</div>';
            $this->renderBreakdown((array) ($pack['price']['breakdown'] ?? []));
            echo '</div>';

            $this->renderProductionDetails($pack);
            $this->renderActions($pack, $redirectUrl);
            $this->renderNotesEditor($pack, $redirectUrl);
            echo '</div>';
            echo '<div class="apd-order-preview">' . wp_kses_post($previewHtml) . '</div>';
            echo '</div>';
            echo '</section>';
        }
        echo '</div>';
    }

    public function renderInlineItemSummary(int $itemId, mixed $item, mixed $product) : void
    {
        if (! is_admin() || ! $item instanceof WC_Order_Item_Product) {
            return;
        }

        $configId = absint($item->get_meta('_apd_config_id', true));
        $userDesignId = absint($item->get_meta('_apd_user_design_id', true));
        $priceAdjustment = (float) $item->get_meta('_apd_price_adjustment', true);
        $priceTotal = (float) $item->get_meta('_apd_price_total', true);
        $resumeUrl = (string) $item->get_meta('_apd_resume_url', true);
        $status = ProductionPackBuilder::statusLabel((string) $item->get_meta('_apd_production_status', true));

        if ($configId <= 0 && $userDesignId <= 0 && abs($priceAdjustment) < 0.00001 && abs($priceTotal) < 0.00001) {
            return;
        }

        echo '<div class="apd-inline-order-summary">';
        echo '<strong>' . esc_html__('Asuka Designer', 'asuka-product-designer') . ':</strong> ';

        $bits = [];
        if ($configId > 0) {
            $bits[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Custom Product #%s', 'asuka-product-designer'), (string) $configId);
        }
        if ($userDesignId > 0) {
            $bits[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Design #%s', 'asuka-product-designer'), (string) $userDesignId);
        }
        $bits[] = $status;
        if (abs($priceAdjustment) >= 0.00001) {
            $bits[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Adjustment %s', 'asuka-product-designer'), wp_strip_all_tags(wc_price($priceAdjustment)));
        }
        if (abs($priceTotal) >= 0.00001) {
            $bits[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Final %s', 'asuka-product-designer'), wp_strip_all_tags(wc_price($priceTotal)));
        }

        echo esc_html(implode(' · ', $bits));
        if ($resumeUrl !== '') {
            echo '<br><a href="' . esc_url($resumeUrl) . '">' . esc_html__('Open saved customization', 'asuka-product-designer') . '</a>';
        }
        echo '</div>';
    }

    protected function renderProductionDetails(array $pack) : void
    {
        $analysis = is_array($pack['analysis'] ?? null) ? $pack['analysis'] : [];
        echo '<div class="apd-order-production">';
        echo '<p class="apd-order-section-title"><strong>' . esc_html__('Production details', 'asuka-product-designer') . '</strong></p>';
        echo '<ul class="apd-order-rules">';
        echo '<li><strong>' . esc_html__('Views', 'asuka-product-designer') . '</strong>: ' . sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('%1$d views · %2$d objects', 'asuka-product-designer'), (int) ($analysis['viewCount'] ?? 0), (int) ($analysis['objectCount'] ?? 0)) . '</li>';
        echo '<li><strong>' . esc_html__('Object types', 'asuka-product-designer') . '</strong>: ' . esc_html(implode(', ', (array) ($analysis['objectTypes'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Colors', 'asuka-product-designer') . '</strong>: ' . esc_html(implode(', ', (array) ($analysis['colors'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Texts', 'asuka-product-designer') . '</strong>: ' . esc_html(implode(' · ', (array) ($analysis['texts'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Printing methods', 'asuka-product-designer') . '</strong>: ' . esc_html(implode(', ', (array) ($analysis['printingMethods'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        if (! empty($pack['productionNotes'])) {
            echo '<li><strong>' . esc_html__('Workshop notes', 'asuka-product-designer') . '</strong>: ' . nl2br(esc_html((string) $pack['productionNotes'])) . '</li>';
        }
        echo '</ul>';
        echo '</div>';
    }

    protected function renderNotesEditor(array $pack, string $redirectUrl) : void
    {
        $action = esc_url(admin_url('admin-post.php'));
        echo '<form class="apd-order-notes" method="post" action="' . esc_url($action) . '">';
        echo '<input type="hidden" name="action" value="apd_save_production_notes">';
        echo '<input type="hidden" name="order_id" value="' . (int) ($pack['orderId'] ?? 0) . '">';
        echo '<input type="hidden" name="item_id" value="' . (int) ($pack['itemId'] ?? 0) . '">';
        echo '<input type="hidden" name="redirect" value="' . esc_attr(rawurlencode($redirectUrl)) . '">';
        wp_nonce_field('apd_update_production_notes_' . (int) ($pack['orderId'] ?? 0) . '_' . (int) ($pack['itemId'] ?? 0));
        echo '<label><strong>' . esc_html__('Workshop notes', 'asuka-product-designer') . '</strong></label>';
        echo '<textarea name="notes" rows="4" placeholder="' . esc_attr__('Add internal production notes, finishing instructions, or QA remarks…', 'asuka-product-designer') . '">' . esc_textarea((string) ($pack['productionNotes'] ?? '')) . '</textarea>';
        echo '<div class="apd-order-notes__actions">';
        submit_button(__('Save notes', 'asuka-product-designer'), 'secondary', '', false);
        echo '</div>';
        echo '</form>';
    }

    protected function renderActions(array $pack, string $redirectUrl) : void
    {
        echo '<div class="apd-order-actions">';
        echo '<a class="button button-primary" href="' . esc_url((string) ($pack['downloads']['worksheet'] ?? '')) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Printable worksheet', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['pack'] ?? '')) . '">' . esc_html__('Production pack', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['summary'] ?? '')) . '">' . esc_html__('Summary JSON', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['design'] ?? '')) . '">' . esc_html__('Design JSON', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['state'] ?? '')) . '">' . esc_html__('State JSON', 'asuka-product-designer') . '</a> ';
        if (! empty($pack['previewUrl'])) {
            echo '<a class="button button-link" href="' . esc_url((string) $pack['previewUrl']) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Open HD preview', 'asuka-product-designer') . '</a>';
        }
        echo '</div>';

        echo '<div class="apd-order-statusbar">';
        echo '<strong>' . esc_html__('Status', 'asuka-product-designer') . ':</strong> ';
        foreach (ProductionPackBuilder::statusOptions() as $status => $label) {
            $url = ProductionPackBuilder::buildStatusUrl((int) $pack['orderId'], (int) $pack['itemId'], $status, $redirectUrl);
            $class = $status === ($pack['productionStatus'] ?? '') ? 'button button-primary' : 'button button-secondary';
            echo '<a class="' . esc_attr($class) . '" href="' . esc_url($url) . '">' . esc_html($label) . '</a> ';
        }
        echo '</div>';
    }

    protected function renderBreakdown(array $breakdown) : void
    {
        $rows = is_array($breakdown['breakdown'] ?? null) ? $breakdown['breakdown'] : [];
        $rules = is_array($breakdown['appliedRules'] ?? null) ? $breakdown['appliedRules'] : [];

        if ($rows === [] && $rules === []) {
            echo '<p class="apd-order-empty apd-order-empty-spaced">' . esc_html__('No pricing breakdown captured for this item.', 'asuka-product-designer') . '</p>';
            return;
        }

        if ($rows !== []) {
            echo '<ul class="apd-order-rules">';
            foreach ($rows as $row) {
                if (! is_array($row)) {
                    continue;
                }
                $type = (string) ($row['type'] ?? __('Entry', 'asuka-product-designer'));
                $amount = (float) ($row['amount'] ?? 0);
                echo '<li><strong>' . esc_html($this->humanizeBreakdownLabel($type)) . '</strong>: ' . wp_kses_post(wc_price($amount)) . '</li>';
            }
            echo '</ul>';
        }

        if ($rules !== []) {
            echo '<p class="apd-order-section-title"><strong>' . esc_html__('Applied pricing rules', 'asuka-product-designer') . '</strong></p>';
            echo '<ul class="apd-order-rules">';
            foreach ($rules as $rule) {
                if (! is_array($rule)) {
                    continue;
                }
                $label = (string) ($rule['label'] ?? $rule['handler'] ?? __('Rule', 'asuka-product-designer'));
                $amount = (float) ($rule['amount'] ?? 0);
                echo '<li>' . esc_html($label) . ': ' . wp_kses_post(wc_price($amount)) . '</li>';
            }
            echo '</ul>';
        }
    }

    protected function humanizeBreakdownLabel(string $type) : string
    {
        $map = [
            'base' => __('WooCommerce base', 'asuka-product-designer'),
            'fixed_fee' => __('Fixed fee', 'asuka-product-designer'),
            'designer_base' => __('Designer base price', 'asuka-product-designer'),
            'standard' => __('Standard add-ons', 'asuka-product-designer'),
            'rules' => __('Rules total', 'asuka-product-designer'),
        ];

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

    protected function renderPostReference(int $postId) : string
    {
        $title = get_the_title($postId);
        $label = $title !== '' ? $title : ('#' . $postId);

        if (! current_user_can('edit_post', $postId)) {
            return esc_html($label . ' (#' . $postId . ')');
        }

        $url = get_edit_post_link($postId, '');
        if (! $url) {
            return esc_html($label . ' (#' . $postId . ')');
        }

        return sprintf('<a href="%1$s">%2$s</a> <span class="description">#%3$d</span>', esc_url($url), esc_html($label), (int) $postId);
    }

    protected function resolveOrder(mixed $postOrOrderObject) : ?WC_Order
    {
        if ($postOrOrderObject instanceof WC_Order) {
            return $postOrOrderObject;
        }

        if (is_object($postOrOrderObject) && isset($postOrOrderObject->ID)) {
            $order = wc_get_order((int) $postOrOrderObject->ID);
            return $order instanceof WC_Order ? $order : null;
        }

        $query = RequestData::query();
        $orderId = absint($query['id'] ?? 0);
        if ($orderId <= 0) {
            $orderId = absint($query['post'] ?? 0);
        }
        if ($orderId <= 0) {
            return null;
        }

        $order = wc_get_order($orderId);
        return $order instanceof WC_Order ? $order : null;
    }

    protected function renderStyles() : void
    {
    }
}
