<?php

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

trait RuleSummaries
{
    protected function renderAccountsRulesListHtml(int $form_id, array $rules): string
    {
        $rules = array_values(array_filter($rules, 'is_array'));

        if (empty($rules)) {
            return '<div class="text-muted mb-3">' . esc_html__('No user registration workflows are configured for this form yet.', 'griffinforms-form-builder') . '</div>'
                . $this->renderAccountsAddRuleSlab();
        }

        $field_options = $this->getFormFieldOptions($form_id);
        $messages = $this->getMessageOptions();
        $roles = $this->getRoleOptions();

        $html = '';
        foreach ($rules as $index => $rule) {
            $html .= $this->renderAccountsRuleSummaryHtml($rule, $index, $field_options, $messages, $roles);
        }

        $html .= $this->renderAccountsAddRuleSlab();

        return $html;
    }

    protected function renderAccountsRuleSummaryHtml(array $rule, int $index, array $field_options, array $messages, array $roles): string
    {
        $rule_number = $index + 1;
        $email_label = $this->findOptionLabelById($field_options['email_fields'] ?? array(), (int) ($rule['email_field_id'] ?? 0), __('Unmapped email field', 'griffinforms-form-builder'));
        $role_label = $this->findRoleLabel($roles, (string) ($rule['role'] ?? 'subscriber'));
        $mode_label = $this->getCreationModeLabel((string) ($rule['creation_mode'] ?? 'immediate_create'));
        $password_label = $this->getPasswordModeLabel((string) ($rule['password_mode'] ?? 'mapped_password'));
        $message_label = $this->findOptionLabelById($messages, (int) ($rule['confirmation_message_id'] ?? 0), __('Choose a message', 'griffinforms-form-builder'));
        $is_enabled = !empty($rule['enabled']);
        $status_label = $is_enabled ? __('Enabled', 'griffinforms-form-builder') : __('Disabled', 'griffinforms-form-builder');
        $status_badge_class = $is_enabled
            ? 'badge text-bg-light border fw-normal'
            : 'badge text-bg-danger-subtle text-danger-emphasis border border-danger-subtle fw-normal';

        $summary = array_filter(array(
            $email_label,
            $mode_label,
            $password_label,
            !empty($rule['send_confirmation_email'])
                ? sprintf(__('Confirmation email on', 'griffinforms-form-builder'))
                : __('Confirmation email off', 'griffinforms-form-builder'),
        ));

        $html  = '<div class="griffinforms-accounts-rule-item border-bottom py-3 px-2 mb-2 d-flex align-items-center justify-content-between" data-gf-account-rule-id="' . esc_attr((string) ($rule['id'] ?? '')) . '">';
        $html .= '<div class="griffinforms-accounts-rule-header mb-1">';
        $html .= '<div class="mb-2"><span class="fw-semibold">' . esc_html(sprintf(__('User Registration %d', 'griffinforms-form-builder'), $rule_number)) . '</span></div>';
        $html .= '<div class="small mb-1">' . esc_html(implode(' • ', $summary)) . '</div>';
        $html .= '<div class="d-flex flex-wrap gap-2">';
        $html .= '<span class="' . esc_attr($status_badge_class) . '">' . esc_html($status_label) . '</span>';
        $html .= '<span class="badge text-bg-light border fw-normal">' . esc_html($role_label) . '</span>';
        $html .= '<span class="badge text-bg-light border fw-normal">' . esc_html($mode_label) . '</span>';
        if (!empty($rule['send_confirmation_email'])) {
            $html .= '<span class="badge text-bg-light border fw-normal">' . esc_html($message_label) . '</span>';
        }
        $html .= '</div>';
        $html .= '</div>';
        $html .= '<div class="griffinforms-accounts-rule-actions d-flex align-items-center">';
        $html .= '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn me-2 griffinforms-accounts-rule-edit">' . esc_html__('Edit', 'griffinforms-form-builder') . '</button>';
        $html .= '<button type="button" class="gf-btn-light btn griffinforms-app-fe-btn gf-text-danger griffinforms-accounts-rule-delete">' . esc_html__('Delete', 'griffinforms-form-builder') . '</button>';
        $html .= '</div>';
        $html .= '</div>';

        return $html;
    }

    protected function renderAccountsAddRuleSlab(): string
    {
        return '<div class="griffinforms-add-rule-slab border rounded p-3 text-center text-muted" role="button" tabindex="0">'
            . '<span class="dashicons dashicons-plus-alt2"></span>'
            . '<small class="ms-1">' . esc_html__('Add User Registration', 'griffinforms-form-builder') . '</small>'
            . '</div>';
    }

    protected function findOptionLabelById(array $options, int $id, string $fallback): string
    {
        foreach ($options as $option) {
            if (!is_array($option)) {
                continue;
            }

            if ((int) ($option['id'] ?? 0) === $id) {
                return (string) ($option['label'] ?? $fallback);
            }
        }

        return $fallback;
    }

    protected function findRoleLabel(array $roles, string $role_key): string
    {
        foreach ($roles as $role) {
            if (!is_array($role)) {
                continue;
            }

            if ((string) ($role['value'] ?? '') === $role_key) {
                return (string) ($role['label'] ?? $role_key);
            }
        }

        return $role_key !== '' ? $role_key : __('Subscriber', 'griffinforms-form-builder');
    }

    protected function getCreationModeLabel(string $mode): string
    {
        $labels = array(
            'immediate_create' => __('Create automatically', 'griffinforms-form-builder'),
            'pending_admin_activation' => __('Approve before creating the user', 'griffinforms-form-builder'),
            'manual_review_only' => __('Review first, then decide', 'griffinforms-form-builder'),
        );

        return $labels[$mode] ?? $mode;
    }

    protected function getPasswordModeLabel(string $mode): string
    {
        $labels = array(
            'mapped_password' => __('Password field', 'griffinforms-form-builder'),
            'generate_password' => __('Password setup email', 'griffinforms-form-builder'),
        );

        return $labels[$mode] ?? $mode;
    }
}
