{% extends 'clean_base.axml' %}
{% from 'actions.axml' import pagination %}

{% set modal_name = 'Create Subscription' %}

{% macro commander() %}
{
    isFilterable: false,
    idSearch: '',
    eventSearch: '',
    producerSearch: '',
    endpointSearch: '',
    descriptionSearch: '',
    whenFilter: '',

    filterResults(){
        let base = `/v1/subscriptions?pagination=${this.pagination}&page=1`
        if(this.idSearch) base += `&id=${this.idSearch}`
        if(this.eventSearch) base += `&event=${this.eventSearch}`
        if(this.producerSearch) base += `&producer=${this.producerSearch}`
        if(this.endpointSearch) base += `&endpoint=${this.endpointSearch}`
        if(this.descriptionSearch) base += `&description=${this.descriptionSearch}`
        if(this.whenFilter) base += `&timeline=${this.whenFilter}`
        fetch(base)
            .then(r => r.json())
            .then(data => {
                isFiltering = true;
                subscriptions = data;
            }).catch(err => ShowFeedback('error', 'Filter operation failed'))
    },

    clearFilter(){
        this.idSearch = '';
        this.eventSearch = '';
        this.producerSearch = '';
        this.endpointSearch = '';
        this.descriptionSearch = '';
        this.whenFilter = '';
        isFiltering = false;
        fetchAll();
    },

    checkDirty(){
        this.isFilterable = (
            this.idSearch !== '' || this.eventSearch !== '' ||
            this.producerSearch !== '' || this.endpointSearch !== '' ||
            this.descriptionSearch !== '' || this.whenFilter !== ''
        );
        return this.isFilterable;
    }
}
{% endmacro %}


{% block easel %}
<section x-data="{{ controller('subscriptions') }}">
    <div x-data="{{ commander() }}" x-effect="checkDirty">

        <div class="page-content-scroll">
            <div class="page-header d-flex align-items-start justify-content-between">
                <div>
                    <h1 class="page-title">Subscriptions</h1>
                    <p class="page-subtitle">Webhook endpoints subscribed to event actions</p>
                </div>
                <div class="loading-spinner" x-show="loading" x-transition>
                    <div class="spinner-border spinner-border-sm"></div>
                    <span>Loading...</span>
                </div>
            </div>

            <div class="filter-bar">
                <div class="input-icon">
                    <span class="material-icons">tag</span>
                    <input class="form-control" type="text" placeholder="ID" x-model="idSearch"
                        style="width: 80px;">
                </div>
                <div class="input-icon">
                    <span class="material-icons">layers</span>
                    <input class="form-control" type="text" placeholder="Producer..."
                        x-model="producerSearch" style="width: 160px;">
                </div>
                <div class="input-icon">
                    <span class="material-icons">bolt</span>
                    <input class="form-control" type="text" placeholder="Event name..."
                        x-model="eventSearch" style="width: 170px;">
                </div>
                <div class="input-icon">
                    <span class="material-icons">link</span>
                    <input class="form-control" type="text" placeholder="Endpoint..."
                        x-model="endpointSearch" style="width: 170px;">
                </div>
                <select class="form-select" x-model="whenFilter" style="width: 140px;">
                    <option value="">Any Time</option>
                    <option value="today">Today</option>
                    <option value="week">This Week</option>
                    <option value="month">This Month</option>
                </select>
                <button class="btn btn-dark btn-sm d-inline-flex align-items-center gap-1"
                    @click="filterResults" :disabled="!isFilterable">
                    <span class="material-icons" style="font-size: 16px;">search</span>
                    Search
                </button>
                <button class="btn btn-sm btn-outline-secondary" @click="clearFilter"
                    :disabled="!isFiltering" x-show="isFiltering" x-transition>
                    Clear
                </button>
            </div>
        </div>

        <div class="page-table-area">
            <div class="data-table-wrapper" x-init="fetchAll()">
                <div class="data-table-scroll">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th style="width: 8%">ID</th>
                                <th style="width: 18%">Application</th>
                                <th style="width: 20%">Action</th>
                                <th>Endpoint</th>
                                <th style="width: 8%">Retries</th>
                                <th style="width: 18%">Timestamp</th>
                            </tr>
                        </thead>
                        <tbody @refresher.window="refreshPage">
                            <template x-for="sub in subscriptions" :key="sub.subscription">
                                <tr>
                                    <td>
                                        <span class="tag-id" x-text="sub.subscription"></span>
                                    </td>
                                    <td>
                                        <span class="fw-medium" x-text="sub.application"></span>
                                    </td>
                                    <td>
                                        <span x-text="sub.action"></span>
                                    </td>
                                    <td>
                                        <code class="font-mono text-sm" x-text="sub.endpoint"></code>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary bg-opacity-10 text-secondary"
                                            x-text="sub.max_retries"></span>
                                    </td>
                                    <td>
                                        <span class="text-muted-custom text-sm" x-text="sub.timestamped"></span>
                                    </td>
                                </tr>
                            </template>
                            <template x-if="subscriptions.length === 0 && !loading">
                                <tr>
                                    <td colspan="6">
                                        <div class="empty-state">
                                            <span class="material-icons">rss_feed</span>
                                            <p>No subscriptions found</p>
                                        </div>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
                {{ pagination() }}
            </div>
        </div>

    </div>
</section>
{% endblock %}


{% block wizard %}
<span x-data="{
    applications: [],
    actions: [],
    application: '',
    secret: '',
    action: '',
    handler: '',
    max_retries: 3,
    actionContainer: '',

    fetchApplications(){
        fetch('/v1/applications')
            .then(r => r.ok ? r.json() : Promise.reject())
            .then(data => this.applications = data)
            .catch(() => {})
    },

    fetchActions(){
        fetch(`/v1/actions?application=${this.actionContainer}`)
            .then(r => r.ok ? r.json() : Promise.reject())
            .then(data => this.actions = data)
            .catch(() => {})
    },

    resetForm(){
        this.handler = '';
        this.application = '';
        this.action = '';
        this.secret = '';
        this.max_retries = 3;
        this.actionContainer = '';
    },

    saveSubscription(){
        superpost('/v1/subscriptions').send({
            application: this.application,
            secret: this.secret,
            action: this.action,
            max_retries: this.max_retries,
            handler: this.handler
        }).then(res => {
            ShowFeedback('success', 'Subscription created');
            this.resetForm();
            $dispatch('refresher');
            showModal = false;
        }).catch(err => {
            supertoast('error', err.response?.body?.error || 'Failed to create subscription');
        })
    },

    get Activated(){
        if(!this.application.length) return '';
        const activated = this.applications.find(app => app.application === this.application);
        return activated ? activated.address : '';
    }
}">
    <div class="modal-body">
        <div class="row g-3 mb-3">
            <div class="col-7">
                <label class="form-label-sm">Subscriber Application</label>
                <select class="form-select" x-model="application" x-init="fetchApplications">
                    <option value="">Select Application...</option>
                    <template x-for="a in applications">
                        <option :value="a.application" x-text="a.application"></option>
                    </template>
                </select>
            </div>
            <div class="col-5">
                <label class="form-label-sm">Secret Key</label>
                <div x-data="{visible: false}" class="position-relative">
                    <input :type="visible ? 'text' : 'password'" class="form-control pe-5"
                        placeholder="App secret" x-model="secret">
                    <button class="btn btn-link position-absolute end-0 top-50 translate-middle-y text-muted p-1 me-1"
                        @click="visible = !visible" type="button" style="z-index: 3;">
                        <span class="material-icons" style="font-size: 18px;"
                            x-text="visible ? 'visibility' : 'visibility_off'"></span>
                    </button>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-6">
                <label class="form-label-sm">Publisher Application</label>
                <select class="form-select" x-model="actionContainer">
                    <option value="">Select Publisher...</option>
                    <template x-for="app in applications">
                        <option :value="app.application" x-text="app.application"></option>
                    </template>
                </select>
            </div>
            <div class="col-6">
                <label class="form-label-sm">Action</label>
                <select class="form-select" x-model="action"
                    x-effect="if(actionContainer.length) fetchActions()">
                    <option value="">Select Action...</option>
                    <template x-for="dat in actions">
                        <option :value="dat.action" x-text="dat.action"></option>
                    </template>
                </select>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label-sm">Max Retries</label>
            <input type="number" class="form-control" style="width: 100px;" x-model.number="max_retries">
        </div>

        <div class="mb-0">
            <label class="form-label-sm">Handler URL</label>
            <div class="d-flex align-items-center gap-2">
                <span class="font-mono text-sm fw-bold"
                    :class="Activated.length ? 'text-primary' : 'text-danger'"
                    x-text="Activated || 'http://address:port'"></span>
                <input type="text" class="form-control" placeholder="/webhook/handler-path"
                    x-model="handler">
            </div>
        </div>
    </div>

    <div class="modal-footer">
        <button class="btn btn-sm btn-outline-secondary" @click="showModal = false">Cancel</button>
        <button class="btn btn-sm btn-dark d-inline-flex align-items-center gap-1" @click="saveSubscription">
            <span class="material-icons" style="font-size: 16px;">save</span>
            Save Subscription
        </button>
    </div>
</span>
{% endblock %}
