<?php

namespace GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls;

use GriffinForms\Includes\Helpers\Currency;
use GriffinForms\Settings;

class Payment extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls\Format
{
    public function getHtml()
    {
        // Pull configured products; if none, show an empty state (no fake products).
        $products = array();
        if (method_exists($this->item, 'getProp')) {
            $products = $this->item->getProp('field_options');
            // Treat untouched sample/default product as "no products configured" for preview cleanliness.
            if (is_array($products) && count($products) === 1) {
                $only = reset($products);
                $is_default_sample = isset($only['name'], $only['description'], $only['price']) &&
                    $only['name'] === __('Sample Product', 'griffinforms-form-builder') &&
                    $only['description'] === __('Describe the product benefits or what is included.', 'griffinforms-form-builder') &&
                    (float) $only['price'] === 25.0;
                if ($is_default_sample) {
                    $products = array();
                }
            }
        }

        $field_id = method_exists($this->item, 'getProp') ? (string) $this->item->getProp('id') : '';

        // Always enqueue media so wp.media is available for the canvas Browse button
        // regardless of whether products exist yet.
        wp_enqueue_media();

        // If no products are configured, render an empty state notice.
        if (!is_array($products) || empty($products)) {
            echo '<div class="griffinforms-payment-preview alert alert-secondary bg-light text-muted border-0" data-gf-payment-field-id="' . esc_attr($field_id) . '">';
            echo esc_html__('No products configured. Add products in the Payment field settings to preview.', 'griffinforms-form-builder');
            echo '</div>';
            echo '<div class="gf-payment-product-canvas" hidden>';
            $this->renderProductCanvas();
            echo '</div>';
            return;
        }

        // Render field styles so preview items inherit theme styling.
        $this->renderFieldStyles(array('text_input'));
        $this->renderOptionLabelStyles();

        $style_group = esc_attr($this->getFieldStyleGroupId());
        $settings = Settings::getInstance();
        $currency_code = $settings->getOption('payment_currency', 'USD');
        $currency_helper = Currency::getInstance();
        $has_any_images = false;
        foreach ($products as $prod_check) {
            if (!empty($prod_check['image'])) {
                $has_any_images = true;
                break;
            }
        }
        $layout = 'cards';
        if (method_exists($this->item, 'getProp')) {
            $settings = $this->item->getProp('field_settings');
            if (is_array($settings) && !empty($settings['layout'])) {
                $layout = sanitize_key($settings['layout']);
            }
        }
        $layout = in_array($layout, array('cards', 'list'), true) ? $layout : 'cards';
        $list_class = $layout === 'cards' ? 'gf-preview-grid' : 'gf-preview-stack';

        // Lightweight layout styling scoped to the preview (fallbacks when no theme is set).
        $card_fallback = $this->isThemeSet() ? '' : 'background: #fff; border: 1px solid #e5e7eb;';
        echo '<style>
        .griffinforms-payment-preview .gf-preview-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
        .griffinforms-payment-preview .gf-preview-stack { display: grid; gap: 10px; }
        .griffinforms-payment-preview .gf-preview-item { ' . $card_fallback . ' border-radius: 12px; padding: 14px; display: grid; gap: 10px; }
        .griffinforms-payment-preview .gf-preview-item h6 { margin: 0; }
        .griffinforms-payment-preview .gf-preview-media { margin-bottom: 2px; width: 100%; }
        .griffinforms-payment-preview .gf-preview-media img { width: 100%; height: 140px; object-fit: cover; border-radius: 10px; background: rgba(0,0,0,0.03); }
        .griffinforms-payment-preview .gf-preview-media--placeholder { width: 100%; height: 140px; border-radius: 10px; background: rgba(0,0,0,0.06); }
        .griffinforms-payment-preview .gf-preview-media--stack { width: 160px; flex-shrink: 0; margin-bottom: 0; }
        .griffinforms-payment-preview .gf-preview-media--stack img,
        .griffinforms-payment-preview .gf-preview-media--placeholder.gf-preview-media--stack { height: 140px; width: 160px; }
        .griffinforms-payment-preview .gf-preview-item * { text-align: left; }
        </style>';

        echo '<div class="griffinforms-payment-preview" data-gf-payment-field-id="' . esc_attr($field_id) . '">';
        echo '<div class="' . esc_attr($list_class) . '">';

        $total_products = count($products);

        foreach ($products as $product_index => $product) {
            $name       = isset($product['name']) ? $product['name'] : __('Product', 'griffinforms-form-builder');
            $price      = isset($product['price']) ? $product['price'] : 0;
            $desc       = isset($product['description']) ? $product['description'] : '';
            $image      = isset($product['image']) ? $product['image'] : '';
            $product_id = isset($product['id']) ? $product['id'] : '';

            $is_stack   = ($layout === 'list');
            $item_class = 'gf-preview-item' . ($is_stack ? ' gf-preview-item--stack' : '') . ' gf-payment-product-card';

            echo '<div class="' . esc_attr($item_class) . '" data-gf-style-group="' . $style_group . '" data-gf-style-type="text_input"';
            echo ' data-gf-product-id="' . esc_attr($product_id) . '">';

            $this->renderProductSubToolbar($product_index, $total_products, !empty($image), $is_stack);

            if ($is_stack) {
                echo '<div class="d-flex align-items-start gap-3">';
                if (!empty($image)) {
                    echo '<div class="gf-preview-media gf-preview-media--stack gf-payment-image-wrap">';
                    echo '<img src="' . esc_url($image) . '" alt="' . esc_attr($name) . '">';
                    echo '</div>';
                } elseif ($has_any_images) {
                    echo '<div class="gf-preview-media gf-preview-media--placeholder gf-preview-media--stack gf-payment-image-placeholder">';
                    echo '<button type="button" class="gf-payment-add-image-btn gf-btn gf-btn-sm btn-outline-secondary">' . esc_html__('Add Image', 'griffinforms-form-builder') . '</button>';
                    echo '</div>';
                }
                echo '<div class="flex-grow-1">';
                echo '<div class="d-flex justify-content-between align-items-start">';
                echo '<span class="fw-semibold gf-choice-option-label gf-payment-product-name-editable" contenteditable="true" spellcheck="false"';
                echo ' data-gf-prev-value="' . esc_attr($name) . '">';
                echo esc_html($name);
                echo '</span>';
                echo '<span class="fw-semibold gf-payment-product-price-wrap" style="white-space:nowrap;">';
                echo '<span class="gf-payment-product-currency-symbol">' . esc_html($currency_helper->getCurrencySymbol($currency_code)) . '</span>';
                echo '<span class="gf-choice-option-label gf-payment-product-price-editable" contenteditable="true" spellcheck="false" inputmode="decimal"';
                echo ' data-gf-prev-value="' . esc_attr(number_format((float) $price, 2, '.', '')) . '"';
                echo ' data-gf-raw-price="' . esc_attr(number_format((float) $price, 2, '.', '')) . '">';
                echo esc_html(number_format((float) $price, 2, '.', ''));
                echo '</span>';
                echo '</span>';
                echo '</div>';
                if (!empty($desc)) {
                    echo '<div class="small mt-1 mb-2 gf-choice-option-label gf-payment-product-desc-editable" contenteditable="true" spellcheck="false"';
                    echo ' data-gf-style-group="' . $style_group . '" data-gf-style-type="field_description"';
                    echo ' data-gf-prev-value="' . esc_attr($desc) . '">';
                    echo esc_html($desc);
                    echo '</div>';
                } else {
                    echo '<div class="small mt-1 mb-2 gf-choice-option-label gf-payment-product-desc-editable gf-payment-product-desc-empty" contenteditable="true" spellcheck="false"';
                    echo ' data-gf-style-group="' . $style_group . '" data-gf-style-type="field_description"';
                    echo ' data-gf-prev-value="">';
                    echo '</div>';
                }
                echo '<div class="d-flex align-items-center gap-2" style="line-height:1.1;">';
                echo '<input type="checkbox" disabled style="margin:0;">';
                echo '<span class="fw-semibold">' . esc_html__('Include this item', 'griffinforms-form-builder') . '</span>';
                echo '</div>';
                echo '</div>';
                echo '</div>'; // flex wrapper
            } else {
                if (!empty($image)) {
                    echo '<div class="gf-preview-media gf-payment-image-wrap">';
                    echo '<img src="' . esc_url($image) . '" alt="' . esc_attr($name) . '">';
                    echo '</div>';
                } elseif ($has_any_images) {
                    echo '<div class="gf-preview-media gf-preview-media--placeholder gf-payment-image-placeholder">';
                    echo '<button type="button" class="gf-payment-add-image-btn gf-btn gf-btn-sm btn-outline-secondary">' . esc_html__('Add Image', 'griffinforms-form-builder') . '</button>';
                    echo '</div>';
                }
                echo '<div class="d-flex justify-content-between align-items-start">';
                echo '<span class="fw-semibold gf-choice-option-label gf-payment-product-name-editable" contenteditable="true" spellcheck="false"';
                echo ' data-gf-prev-value="' . esc_attr($name) . '">';
                echo esc_html($name);
                echo '</span>';
                echo '<span class="fw-semibold gf-payment-product-price-wrap" style="white-space:nowrap;">';
                echo '<span class="gf-payment-product-currency-symbol">' . esc_html($currency_helper->getCurrencySymbol($currency_code)) . '</span>';
                echo '<span class="gf-choice-option-label gf-payment-product-price-editable" contenteditable="true" spellcheck="false" inputmode="decimal"';
                echo ' data-gf-prev-value="' . esc_attr(number_format((float) $price, 2, '.', '')) . '"';
                echo ' data-gf-raw-price="' . esc_attr(number_format((float) $price, 2, '.', '')) . '">';
                echo esc_html(number_format((float) $price, 2, '.', ''));
                echo '</span>';
                echo '</span>';
                echo '</div>';
                if (!empty($desc)) {
                    echo '<div class="small mt-1 mb-2 gf-choice-option-label gf-payment-product-desc-editable" contenteditable="true" spellcheck="false"';
                    echo ' data-gf-style-group="' . $style_group . '" data-gf-style-type="field_description"';
                    echo ' data-gf-prev-value="' . esc_attr($desc) . '">';
                    echo esc_html($desc);
                    echo '</div>';
                } else {
                    echo '<div class="small mt-1 mb-2 gf-choice-option-label gf-payment-product-desc-editable gf-payment-product-desc-empty" contenteditable="true" spellcheck="false"';
                    echo ' data-gf-style-group="' . $style_group . '" data-gf-style-type="field_description"';
                    echo ' data-gf-prev-value="">';
                    echo '</div>';
                }
                echo '<div class="d-flex align-items-center gap-2" style="line-height:1.1;">';
                echo '<input type="checkbox" disabled style="margin:0;">';
                echo '<span class="fw-semibold">' . esc_html__('Include this item', 'griffinforms-form-builder') . '</span>';
                echo '</div>';
            }

            echo '</div>';
        }

        echo '</div>'; // list/grid
        echo '</div>'; // griffinforms-payment-preview

        echo '<div class="gf-payment-product-canvas" hidden>';
        $this->renderProductCanvas();
        echo '</div>';
    }

    private function renderProductSubToolbar(int $index, int $total, bool $has_image, bool $is_stack)
    {
        $is_first   = ($index === 0);
        $is_last    = ($index === $total - 1);
        $is_only    = ($total === 1);
        $delete_attr = $is_only ? ' disabled' : '';
        $prev_attr   = $is_first ? ' disabled' : '';
        $next_attr   = $is_last  ? ' disabled' : '';
        $remove_img_attr = !$has_image ? ' disabled' : '';

        echo '<div class="gf-sub-toolbar gf-payment-product-toolbar" role="group" aria-label="' . esc_attr__('Product actions', 'griffinforms-form-builder') . '">';

        // Drag handle
        echo '<button type="button" class="gf-sub-toolbar-btn gf-payment-product-drag-handle" aria-label="' . esc_attr__('Drag to reorder', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('drag.svg');
        echo '</button>';

        // Move composite — left/right for cards, up/down for stack
        if ($is_stack) {
            echo '<div class="gf-sub-toolbar-composite">';
            echo '<button type="button" class="gf-sub-toolbar-btn gf-payment-product-move-prev"' . $prev_attr . ' aria-label="' . esc_attr__('Move product up', 'griffinforms-form-builder') . '">';
            $this->echoToolbarSvg('up.svg');
            echo '</button>';
            echo '<button type="button" class="gf-sub-toolbar-btn gf-payment-product-move-next"' . $next_attr . ' aria-label="' . esc_attr__('Move product down', 'griffinforms-form-builder') . '">';
            $this->echoToolbarSvg('down.svg');
            echo '</button>';
            echo '</div>';
        } else {
            echo '<div class="gf-sub-toolbar-composite gf-sub-toolbar-composite--horizontal">';
            echo '<button type="button" class="gf-sub-toolbar-btn gf-payment-product-move-prev"' . $prev_attr . ' aria-label="' . esc_attr__('Move product left', 'griffinforms-form-builder') . '">';
            $this->echoToolbarSvg('left.svg');
            echo '</button>';
            echo '<button type="button" class="gf-sub-toolbar-btn gf-payment-product-move-next"' . $next_attr . ' aria-label="' . esc_attr__('Move product right', 'griffinforms-form-builder') . '">';
            $this->echoToolbarSvg('right.svg');
            echo '</button>';
            echo '</div>';
        }

        // Add / replace image + remove image — grouped so no divider between them
        $this->renderSubToolbarGroup(array(
            array('class' => 'gf-payment-product-image-btn',        'icon' => 'add-image.svg',    'label' => __('Add or replace image', 'griffinforms-form-builder')),
            array('class' => 'gf-payment-product-remove-image-btn', 'icon' => 'remove-image.svg', 'label' => __('Remove image', 'griffinforms-form-builder'), 'disabled' => !$has_image),
        ));

        // Delete product
        echo '<button type="button" class="gf-sub-toolbar-btn gf-payment-product-delete-btn"' . $delete_attr . ' aria-label="' . esc_attr__('Delete product', 'griffinforms-form-builder') . '">';
        $this->echoToolbarSvg('delete-forever.svg');
        echo '</button>';

        echo '</div>';
    }

    private function renderProductCanvas()
    {
        echo '<div class="gf-payment-canvas-header">' . esc_html__('New Product', 'griffinforms-form-builder') . '</div>';
        echo '<div class="mb-2">';
        echo '<label class="form-label">' . esc_html__('Name', 'griffinforms-form-builder') . '</label>';
        echo '<input type="text" class="form-control gf-payment-canvas-name">';
        echo '</div>';
        echo '<div class="mb-2">';
        echo '<label class="form-label">' . esc_html__('Price', 'griffinforms-form-builder') . '</label>';
        echo '<input type="number" class="form-control gf-payment-canvas-price" step="0.01" min="0">';
        echo '</div>';
        echo '<div class="mb-2">';
        echo '<label class="form-label">' . esc_html__('Description', 'griffinforms-form-builder') . '</label>';
        echo '<textarea class="form-control gf-payment-canvas-desc" rows="2"></textarea>';
        echo '</div>';
        echo '<div class="mb-2">';
        echo '<label class="form-label">' . esc_html__('Image', 'griffinforms-form-builder') . '</label>';
        echo '<div class="input-group">';
        echo '<input type="text" class="form-control gf-payment-canvas-image" placeholder="' . esc_attr__('Image URL', 'griffinforms-form-builder') . '" readonly>';
        echo '<button type="button" class="gf-btn gf-btn-outline gf-btn-sm gf-payment-canvas-image-pick">' . esc_html__('Browse', 'griffinforms-form-builder') . '</button>';
        echo '</div>';
        echo '</div>';
        echo '<div class="gf-product-canvas-actions">';
        echo '<button type="button" class="gf-btn gf-btn-primary gf-btn-sm gf-payment-save-product-btn">' . esc_html__('Save Product', 'griffinforms-form-builder') . '</button>';
        echo '<button type="button" class="gf-btn gf-btn-secondary gf-btn-sm gf-payment-cancel-product-btn">' . esc_html__('Cancel', 'griffinforms-form-builder') . '</button>';
        echo '</div>';
    }
}
