<?php

namespace Storeplugin\PDFInvoice\App\Forms;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractSetting;
use Storeplugin\PDFInvoice\Framework\Contracts\SettingInterface;
use Storeplugin\PDFInvoice\Framework\Fields\FieldRenderer;
use Storeplugin\PDFInvoice\App\Utils;
use Storeplugin\PDFInvoice\Config;
use Storeplugin\PDFInvoice\Asset;
use Mpdf\Mpdf;

/**
 * PDF Invoice Editor panel with live preview functionality.
 *
 * Provides a specialized settings page for editing PDF invoice templates
 * with a side-by-side preview panel.
 */
class PDFPanel extends AbstractSetting
{
    /**
     * Shared option name set from InvoicePanel::create(...$optionName...).
     */
    protected static $sharedOptionName = '';

    /**
     * Get the shared option name.
     */
    public static function optionName(): string
    {
        if (static::$sharedOptionName !== '') {
            return static::$sharedOptionName;
        }

        return Config::option('settings_options');
    }

    /**
     * Set the shared option name.
     */
    public static function setOptionName(string $optionName): void
    {
        $optionName = \sanitize_key($optionName);
        if ($optionName !== '') {
            static::$sharedOptionName = $optionName;
        }
    }

    /**
     * Create a new option panel instance
     *
     * @param string $pageTitle   Page title
     * @param string $menuTitle   Menu title
     * @param string $slug        Menu slug
     * @param string $optionName  Option key used for storage
     * @param string $capability  Capability required to access the page
     * @param string $icon        Icon for the menu item
     * @param int    $position    Position of the menu item
     *
     * @return SettingInterface
     */
    public static function create(
        string $pageTitle,
        string $menuTitle,
        string $slug,
        string $optionName,
        string $capability = 'manage_options',
        string $icon = 'dashicons-admin-generic',
        int $position = 25
    ): SettingInterface {
        static::setOptionName($optionName);
        return new self($pageTitle, $menuTitle, $slug, $optionName, $capability, $icon, $position);
    }

    /**
     * Add a tab to the sidebar
     *
     * @param string         $id       Unique tab ID
     * @param string         $title    Display title
     * @param string         $icon     Dashicon slug
     * @param array|callable $sublinks Array of sublinks or callback function receiving Tab instance
     * @return self
     * @throws \Exception Tabs are not supported in the PDF editor panel
     */
    public function addTab(string $id, string $title, string $icon, $sublinks = []): self
    {
        throw new \Exception('Tabs are not supported in the PDF editor panel');
    }

    protected function enqueueAssets(): void
    {
        parent::enqueueAssets();

        Asset::registerAppAdminAssets();
        \wp_enqueue_style(
            Config::asset('style'),
            trailingslashit(NXTPDF_URL) . 'assets/css/style.css',
            [],
            Config::version()
        );
        \wp_enqueue_style(Config::asset('admin-style'));
        \wp_enqueue_script(Config::asset('admin-script'));
    }

    /**
     * Render panels for a group
     *
     * @param array $panels  Panels configuration array
     * @param array $options Current option values
     */
    protected function renderPanels(array $panels, array $options): void
    {
        foreach ($panels as $panelIndex => $panel) {
            $panelIconClass = $this->getDashiconClass($panel['icon'] ?? '', 'admin-generic');

            $rawLayout      = $panel['layout'] ?? 'vertical';
            $layout         = in_array($rawLayout, ['horizontal', 'vertical'], true) ? $rawLayout : 'vertical';
            $rawColSpan     = $panel['default_col_span'] ?? 6;
            $defaultColSpan = is_numeric($rawColSpan) ? max(1, min(12, (int) $rawColSpan)) : 6;

            $containerClass = $layout === 'horizontal'
                ? 'nxtf-grid-layout'
                : 'nxtf-space-y-6';
            $layoutHookClass = $layout === 'horizontal'
                ? 'is-horizontal'
                : 'is-vertical';
        ?>
            <div data-nxtpdf-section<?php echo $panelIndex === 0 ? '' : ' data-collapsed'; ?> class="nxtpdf-panel-section">
                <h3 data-nxtpdf-section-title class="nxtpdf-panel-section-title">
                    <span class="<?php echo \esc_attr($panelIconClass); ?> nxtpdf-panel-section-icon" aria-hidden="true"></span>
                    <?php echo \esc_html($panel['title']); ?>
                    <svg data-nxtpdf-arrow class="nxtpdf-panel-section-arrow" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                    </svg>
                </h3>
                <div data-nxtpdf-section-content class="nxtpdf-panel-section-content">
                    <div class="nxtpdf-panel-fields <?php echo \esc_attr($layoutHookClass); ?> <?php echo \esc_attr($containerClass); ?>">
                        <?php
                            $fields = isset($panel['fields']) && is_array($panel['fields']) ? $panel['fields'] : [];
                            foreach ($fields as $field) {
                                if ($layout === 'horizontal' && !isset($field['col_span'])) {
                                    $fieldType = \sanitize_key($field['type'] ?? '');
                                    if (in_array($fieldType, ['repeater', 'wysiwyg'], true)) {
                                        $field['col_span'] = 12;
                                    } else {
                                        $field['col_span'] = $defaultColSpan;
                                    }
                                }

                                $id = \sanitize_key((string) ($field['id'] ?? ''));
                                if ($id === '') {
                                    continue;
                                }

                                $value = array_key_exists($id, $options) ? $options[$id] : null;
                                FieldRenderer::render($field, $value, $this->getOptionKey());
                            }
                        ?>
                    </div>
                </div>
            </div>
        <?php
        }
    }

    /**
     * Render the option panel page
     *
     * @internal WordPress callback method - do not call directly
     */
    public function renderPage(): void
    {
        $mpdf_installed = class_exists(Mpdf::class);
        $options = Utils::getOptions($this->getOptionKey());
        $panelSlug = \sanitize_title($this->slug);
        ?>
        <div class="wrap">
            <h1 class="nxtpdf-page-title"><?php echo \esc_html($this->pageTitle); ?></h1>
            <?php \settings_errors(Config::option('messages')); ?>

            <?php if (!$mpdf_installed): ?>
            <div class="nxtpdf-mpdf-warning">
                <div class="nxtpdf-mpdf-warning-row">
                    <div class="nxtpdf-mpdf-warning-icon-wrap">
                        <svg class="nxtpdf-mpdf-warning-icon" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                        </svg>
                    </div>
                    <div class="nxtpdf-mpdf-warning-content">
                        <p class="nxtpdf-mpdf-warning-text">
                            <strong>mPDF not installed.</strong> HTML preview is still available, but PDF download and print require <code class="nxtpdf-mpdf-warning-code">composer install</code> in the plugin directory:
                            <code class="nxtpdf-mpdf-warning-code nxtpdf-mpdf-warning-path"><?php echo \esc_html(NXTPDF_DIR); ?></code>
                        </p>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="nxtpdf-editor-layout" style="height: calc(100vh - 180px);">
                <!-- Left Sidebar -->
                <div class="nxtpdf-editor-sidebar">
                    <?php $optionKey = $this->getOptionKey(); ?>
                    <form data-nxtpdf-form data-option-key="<?php echo \esc_attr($optionKey); ?>" method="post" action="">
                        <?php \wp_nonce_field($optionKey . '_action', $optionKey . '_nonce'); ?>

                        <?php foreach ($this->getAllGroups() as $group) : ?>
                            <div id="section-<?php echo \esc_attr($panelSlug . '-' . $group['id']); ?>" class="content-section active" data-section-id="<?php echo \esc_attr($group['id']); ?>">
                                <?php if (!empty($group['title'])) : ?>
                                <header class="nxtpdf-editor-group-header">
                                    <h2 class="nxtpdf-editor-group-title"><?php echo \esc_html($group['title']); ?></h2>
                                    <?php if (!empty($group['description'])) : ?>
                                        <p class="nxtpdf-editor-group-description"><?php echo \esc_html($group['description']); ?></p>
                                    <?php endif; ?>
                                </header>
                                <?php endif; ?>
                                <?php $this->renderPanels($group['panels'], $options); ?>
                            </div>
                        <?php endforeach; ?>

                        <!-- Actions -->
                        <div class="nxtpdf-editor-actions">
                            <button type="button" data-nxtpdf-preview-btn class="nxtpdf-btn nxtpdf-btn-secondary nxtpdf-btn-block">
                                <svg class="nxtpdf-btn-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                </svg>
                                <?php \esc_html_e('Update Preview', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>
                            </button>
                            <button type="submit" data-nxtpdf-save-btn name="<?php echo \esc_attr($optionKey); ?>_save" value="1" class="nxtpdf-btn nxtpdf-btn-primary nxtpdf-btn-block">
                                <svg class="nxtpdf-btn-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                </svg>
                                <?php \esc_html_e('Save Settings', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Right Preview Panel -->
                <div class="nxtpdf-preview-panel">
                    <div class="nxtpdf-preview-toolbar">
                        <h3 class="nxtpdf-preview-toolbar-title"><?php \esc_html_e('Live Preview', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?></h3>
                        <div class="nxtpdf-preview-toolbar-controls">
                            <button type="button" data-nxtpdf-zoom-out class="nxtpdf-icon-btn" title="<?php \esc_attr_e('Zoom Out', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>">
                                <svg class="nxtpdf-icon-btn-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"/>
                                </svg>
                            </button>
                            <span data-nxtpdf-zoom-level class="nxtpdf-zoom-level">100%</span>
                            <button type="button" data-nxtpdf-zoom-in class="nxtpdf-icon-btn" title="<?php \esc_attr_e('Zoom In', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>">
                                <svg class="nxtpdf-icon-btn-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                </svg>
                            </button>
                            <button type="button" data-nxtpdf-download class="nxtpdf-btn nxtpdf-btn-primary nxtpdf-btn-compact" title="<?php \esc_attr_e('Download PDF', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>">
                                <svg class="nxtpdf-btn-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                                </svg>
                                <?php \esc_html_e('Download', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>
                            </button>
                        </div>
                    </div>

                    <div class="nxtpdf-preview-stage">
                        <div data-nxtpdf-loading class="nxtpdf-preview-loading">
                            <svg class="nxtpdf-spinner" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="nxtpdf-spinner-track" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="nxtpdf-spinner-head" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span class="nxtpdf-preview-loading-text"><?php \esc_html_e('Generating preview...', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?></span>
                        </div>

                        <div data-nxtpdf-preview-shell class="nxtpdf-preview-shell">
                            <iframe data-nxtpdf-preview-frame title="<?php \esc_attr_e('Template Preview', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>" scrolling="no"></iframe>
                        </div>

                        <div data-nxtpdf-placeholder data-active class="nxtpdf-preview-placeholder">
                            <svg class="nxtpdf-preview-placeholder-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                            </svg>
                            <p class="nxtpdf-preview-placeholder-text"><?php \esc_html_e('Click "Update Preview" to render the template preview', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?></p>
                            <?php if (!$mpdf_installed): ?>
                            <p class="nxtpdf-preview-placeholder-note"><?php \esc_html_e('PDF download and print will stay unavailable until mPDF is installed.', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Ads Column -->
        <?php $this->renderSidebarCallback(); ?>
    <?php
    }
}
