<?php

namespace GriffinForms\Admin\App\Html\Modals\FormNotifications;

use GriffinForms\Includes\Notifications\NotificationChannelRegistry;
use GriffinForms\Includes\Notifications\NotificationEventRegistry;

trait Markup
{
    protected function renderNotificationsBody(): void
    {
        $form          = $this->utility->getForm();
        $form_id       = (int) $this->utility->getFormId();
        $event_reg     = NotificationEventRegistry::getInstance();
        $channel_reg   = NotificationChannelRegistry::getInstance();
        $events        = $event_reg->getAll();
        $channels      = $channel_reg->getAll();
        $check_nonce   = wp_create_nonce('check_form_fields');
        $create_url    = admin_url('admin.php?page=griffinforms-message');

        // Resolve notifications using the canonical bridge so legacy forms hydrate too.
        $notifications = $form ? NotificationChannelRegistry::resolveFormNotifications($form) : [];

        // Load all messages for the message picker.
        $sql      = \GriffinForms\Admin\Sql\App::getInstance();
        $messages = $sql->getItems('message', ['id', 'name']) ?: [];

        echo '<div class="gf-formoptions-body d-flex h-100">';

        // ── Left tab strip (mirrors Form Options pattern exactly) ──────────
        echo '<nav class="gf-formoptions-sidenav" aria-label="' . esc_attr__('Notifications navigation', 'griffinforms-form-builder') . '">';
        echo '<span class="gf-formoptions-tab-indicator" aria-hidden="true"></span>';

        foreach ($events as $i => $event) {
            $active   = $i === 0 ? ' gf-formoptions-tab-btn--active' : '';
            $selected = $i === 0 ? 'true' : 'false';
            $event_id = $event->getEventId();
            echo '<button class="gf-formoptions-tab-btn' . esc_attr($active) . '"';
            echo ' id="gf-notif-tab-' . esc_attr($event_id) . '"';
            echo ' data-bs-target="#gf-notif-panel-' . esc_attr($event_id) . '"';
            echo ' type="button" role="tab"';
            echo ' aria-controls="gf-notif-panel-' . esc_attr($event_id) . '"';
            echo ' aria-selected="' . esc_attr($selected) . '">';
            echo '<span class="gf-formoptions-tab-btn-label">' . esc_html($event->getLabel()) . '</span>';
            echo '<svg class="gf-formoptions-tab-chevron" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M6 4l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
            echo '</button>';
        }

        echo '</nav>';

        // ── Right content panels ───────────────────────────────────────────
        echo '<div class="gf-formoptions-content" id="gf-notif-tab-content">';

        foreach ($events as $i => $event) {
            $event_id     = $event->getEventId();
            $active_class = $i === 0 ? ' gf-formoptions-panel--active' : '';

            echo '<div class="gf-formoptions-panel' . esc_attr($active_class) . '"';
            echo ' id="gf-notif-panel-' . esc_attr($event_id) . '"';
            echo ' role="tabpanel"';
            echo ' aria-labelledby="gf-notif-tab-' . esc_attr($event_id) . '">';
            echo '<div class="gf-formoptions-panel-body">';

            $coming_soon = ['submission_edit', 'payment_success', 'payment_failed'];

            foreach ($event->getSubEvents() as $sub_event_id => $sub_event_label) {
                $is_coming_soon = in_array($sub_event_id, $coming_soon, true);
                $actions        = $notifications[$event_id][$sub_event_id] ?? [];

                echo '<div class="gf-notif-subevent mb-4"';
                echo ' data-event-id="' . esc_attr($event_id) . '"';
                echo ' data-subevent-id="' . esc_attr($sub_event_id) . '">';

                echo '<div class="d-flex align-items-center justify-content-between mb-2">';
                echo '<div class="d-flex align-items-center gap-2">';
                echo '<h6 class="mb-0 fw-semibold small text-uppercase text-muted">' . esc_html($sub_event_label) . '</h6>';
                if ($is_coming_soon) {
                    echo '<span class="badge gf-notif-coming-soon-badge">' . esc_html__('Coming Soon', 'griffinforms-form-builder') . '</span>';
                }
                echo '</div>';
                if (!$is_coming_soon) {
                    echo '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn gf-notif-card-add"';
                    echo ' data-event-id="' . esc_attr($event_id) . '"';
                    echo ' data-subevent-id="' . esc_attr($sub_event_id) . '">';
                    echo esc_html__('Add', 'griffinforms-form-builder');
                    echo '</button>';
                }
                echo '</div>';

                if ($is_coming_soon) {
                    echo '<p class="text-muted small mb-0">';
                    echo esc_html__('Notifications for this trigger are not yet available.', 'griffinforms-form-builder');
                    echo '</p>';
                } else {
                    // Sortable card list
                    echo '<div class="gf-notif-card-list"';
                    echo ' data-event-id="' . esc_attr($event_id) . '"';
                    echo ' data-subevent-id="' . esc_attr($sub_event_id) . '">';

                    if (empty($actions)) {
                        echo '<p class="text-muted small gf-notif-empty-state">';
                        echo esc_html__('No notifications configured. Click Add to create one.', 'griffinforms-form-builder');
                        echo '</p>';
                    }

                    foreach ($actions as $action) {
                        $this->renderActionCard($action, $channels, $messages, $form_id, $check_nonce);
                    }

                    echo '</div>'; // .gf-notif-card-list
                }

                echo '</div>'; // .gf-notif-subevent
            }

            echo '</div>'; // .gf-formoptions-panel-body
            echo '</div>'; // .gf-formoptions-panel
        }

        echo '</div>'; // .gf-formoptions-content
        echo '</div>'; // .gf-formoptions-body

        // ── Card template (cloned by JS for new cards) ────────────────────
        $this->renderCardTemplate($channels, $messages, $create_url);

        // ── Data for JS ───────────────────────────────────────────────────
        echo '<script id="gf-notif-messages-data" type="application/json">';
        $messages_js = [];
        foreach ($messages as $msg) {
            $messages_js[] = ['id' => (int) $msg->id, 'name' => $msg->name ?: sprintf(__('Message #%d', 'griffinforms-form-builder'), $msg->id)];
        }
        echo wp_json_encode($messages_js);
        echo '</script>';

        echo '<div id="gf-notif-js-data"';
        echo ' data-form-id="' . esc_attr($form_id) . '"';
        echo ' data-check-nonce="' . esc_attr($check_nonce) . '"';
        echo ' data-create-url="' . esc_url($create_url) . '">';
        echo '</div>';
    }

    protected function renderActionCard(array $action, array $channels, array $messages, int $form_id, string $check_nonce): void
    {
        $uuid       = sanitize_text_field($action['id'] ?? wp_generate_uuid4());
        $enabled    = !empty($action['enabled']);
        $channel_id = sanitize_key($action['channel'] ?? '');
        $message_id = absint($action['message_id'] ?? 0);
        $recipients = is_array($action['recipients'] ?? null) ? $action['recipients'] : [];
        $order      = absint($action['order'] ?? 1);

        // Resolve channel — may be null if integration deactivated.
        $channel     = null;
        $channel_reg = NotificationChannelRegistry::getInstance();
        foreach ($channels as $ch) {
            if ($ch->getChannelId() === $channel_id) {
                $channel = $ch;
                break;
            }
        }

        $inactive = ($channel_id !== '' && $channel === null);

        echo '<div class="gf-notif-card"';
        echo ' data-notification-id="' . esc_attr($uuid) . '"';
        echo ' data-order="' . esc_attr($order) . '">';

        // Card header
        echo '<div class="gf-notif-card-header">';
        echo '<span class="gf-notif-card-handle" aria-hidden="true">';
        echo '<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><circle cx="5" cy="4" r="1.2"/><circle cx="5" cy="8" r="1.2"/><circle cx="5" cy="12" r="1.2"/><circle cx="11" cy="4" r="1.2"/><circle cx="11" cy="8" r="1.2"/><circle cx="11" cy="12" r="1.2"/></svg>';
        echo '</span>';

        // Enabled toggle
        $checked = $enabled ? ' checked' : '';
        echo '<input type="checkbox" class="form-check-input gf-app-control-checkbox gf-notif-card-enabled ms-2"' . $checked . ' aria-label="' . esc_attr__('Enable notification', 'griffinforms-form-builder') . '">';

        // Channel badge
        $badge_label = $channel ? esc_html($channel->getLabel()) : ($channel_id !== '' ? esc_html($channel_id . ' ' . __('(inactive)', 'griffinforms-form-builder')) : esc_html__('No channel', 'griffinforms-form-builder'));
        echo '<span class="gf-notif-card-channel-badge badge ms-2">' . $badge_label . '</span>';

        // Expand/collapse chevron
        echo '<span class="gf-notif-card-toggle ms-auto" role="button" aria-expanded="false" aria-label="' . esc_attr__('Toggle notification', 'griffinforms-form-builder') . '">';
        echo '<svg class="gf-notif-card-chevron" viewBox="0 0 16 16" width="16" height="16" fill="none" aria-hidden="true"><path d="M4 6l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
        echo '</span>';

        // Delete button
        echo '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn gf-text-danger gf-notif-card-delete ms-1">';
        echo esc_html__('Delete', 'griffinforms-form-builder');
        echo '</button>';

        echo '</div>'; // .gf-notif-card-header

        // Card body (collapsed by default)
        echo '<div class="gf-notif-card-body" style="display:none;">';

        if ($inactive) {
            echo '<div class="gf-notice gf-notice-danger mb-3">';
            echo esc_html__('The integration for this channel is inactive. Reactivate it to edit.', 'griffinforms-form-builder');
            echo '</div>';
        }

        // Channel select
        echo '<div class="row mb-3 gf-formoptions-row">';
        echo '<div class="col-md-3"><label class="form-label fw-medium small">' . esc_html__('Channel', 'griffinforms-form-builder') . '</label></div>';
        echo '<div class="col-md-9">';
        echo '<select class="form-select gf-app-control-input gf-notif-card-channel"' . ($inactive ? ' disabled' : '') . '>';
        echo '<option value="">' . esc_html__('— Select a channel —', 'griffinforms-form-builder') . '</option>';
        foreach ($channels as $ch) {
            $sel            = $ch->getChannelId() === $channel_id ? ' selected' : '';
            $field_type_attr = $ch->getRequiredFieldType() ? ' data-field-type="' . esc_attr($ch->getRequiredFieldType()) . '"' : '';
            $static_attr    = $ch->supportsStaticRecipients() ? ' data-supports-static="true"' : ' data-supports-static="false"';
            echo '<option value="' . esc_attr($ch->getChannelId()) . '"' . $sel . $field_type_attr . $static_attr . '>' . esc_html($ch->getLabel()) . '</option>';
        }
        echo '</select>';
        echo '</div></div>';

        // Message select
        echo '<div class="row mb-3 gf-formoptions-row">';
        echo '<div class="col-md-3"><label class="form-label fw-medium small">' . esc_html__('Message', 'griffinforms-form-builder') . '</label></div>';
        echo '<div class="col-md-9">';
        $message_disabled = ($inactive || !$channel_id) ? ' disabled' : '';
        echo '<select class="form-select gf-app-control-input gf-notif-card-message"' . $message_disabled . '>';
        echo '<option value="0">' . esc_html__('— Select a message —', 'griffinforms-form-builder') . '</option>';
        foreach ($messages as $msg) {
            $sel = ((int) $msg->id === $message_id) ? ' selected' : '';
            echo '<option value="' . esc_attr($msg->id) . '"' . $sel . '>' . esc_html($msg->name ?: sprintf(__('Message #%d', 'griffinforms-form-builder'), $msg->id)) . '</option>';
        }
        echo '</select>';
        echo '<div class="mt-1"><a href="' . esc_url(admin_url('admin.php?page=griffinforms-message')) . '" target="_blank" rel="noopener noreferrer" class="small gf-notif-create-message-link">' . esc_html__('Create a new message', 'griffinforms-form-builder') . ' &rarr;</a></div>';
        echo '</div></div>';

        // Recipients
        echo '<div class="row mb-2 gf-formoptions-row">';
        echo '<div class="col-md-3"><label class="form-label fw-medium small">' . esc_html__('Recipients', 'griffinforms-form-builder') . '</label></div>';
        echo '<div class="col-md-9">';
        echo '<div class="gf-notif-recipients">';

        $field_type = $channel ? $channel->getRequiredFieldType() : null;
        $supports_static = $channel ? $channel->supportsStaticRecipients() : true;

        if (empty($recipients)) {
            echo '<p class="text-muted small gf-notif-recipients-empty">' . esc_html__('No recipients added.', 'griffinforms-form-builder') . '</p>';
        }

        foreach ($recipients as $recipient) {
            $rtype  = $recipient['type'] ?? 'static';
            $rvalue = $recipient['value'] ?? '';
            $this->renderRecipientRow($rtype, $rvalue, $uuid, $inactive, $field_type);
        }

        echo '</div>'; // .gf-notif-recipients

        // Add recipient button
        if (!$inactive) {
            $field_type_attr = $field_type ? ' data-field-type="' . esc_attr($field_type) . '"' : '';
            echo '<div class="mt-2">';
            echo '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn gf-notif-add-recipient"' . $field_type_attr . '>';
            echo esc_html__('+ Recipient', 'griffinforms-form-builder');
            echo '</button>';
            echo '</div>';
        }

        echo '</div></div>'; // col + row

        echo '</div>'; // .gf-notif-card-body
        echo '</div>'; // .gf-notif-card
    }

    protected function renderRecipientRow(string $type, string $value, string $card_id, bool $disabled = false, ?string $field_type = null): void
    {
        $dis = $disabled ? ' disabled' : '';
        echo '<div class="gf-notif-recipient-row input-group mb-2">';

        // Left: type selector
        echo '<select class="form-select gf-app-control-input gf-notif-recipient-type flex-grow-0 w-auto"' . $dis . '>';
        echo '<option value="field"' . ($type === 'field' ? ' selected' : '') . '>' . esc_html__('Field', 'griffinforms-form-builder') . '</option>';
        echo '<option value="static"' . ($type !== 'field' ? ' selected' : '') . '>' . esc_html__('Custom', 'griffinforms-form-builder') . '</option>';
        echo '</select>';

        // Right: field picker or static input
        if ($type === 'field') {
            $field_type_data = $field_type ? ' data-field-type="' . esc_attr($field_type) . '"' : '';
            echo '<select class="form-select gf-app-control-input gf-notif-recipient-value-field" data-selected="' . esc_attr($value) . '"' . $field_type_data . $dis . '>';
            echo '<option value="' . esc_attr($value) . '">' . esc_html__('Loading…', 'griffinforms-form-builder') . '</option>';
            echo '</select>';
        } else {
            echo '<input type="text" class="form-control gf-app-control-input gf-notif-recipient-value-static"';
            echo ' value="' . esc_attr($value) . '" placeholder="' . esc_attr__('e.g. admin@example.com', 'griffinforms-form-builder') . '"' . $dis . '>';
        }

        if (!$disabled) {
            echo '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn gf-text-danger gf-notif-remove-recipient">';
            echo esc_html__('Delete', 'griffinforms-form-builder');
            echo '</button>';
        }

        echo '</div>'; // .gf-notif-recipient-row
    }

    protected function renderCardTemplate(array $channels, array $messages, string $create_url): void
    {
        echo '<template id="gf-notif-card-template">';
        $this->renderActionCard([
            'id'         => '__UUID__',
            'enabled'    => true,
            'channel'    => '',
            'message_id' => 0,
            'recipients' => [],
            'order'      => 0,
        ], $channels, $messages, 0, '');
        echo '</template>';
    }
}
