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

{% set modal_name = 'Create New Action' %}

{% macro commander() %}
{
    isFilterable: false,
    actionSearch: '',
    applicationSearch: '',
    schemataSearch: '',
    whenFilter: '',

    filterResults(){
        let base = `/v1/actions?pagination=${this.pagination}&page=1`
        if(this.actionSearch) base += `&action=${this.actionSearch}`
        if(this.applicationSearch) base += `&application=${this.applicationSearch}`
        if(this.schemataSearch) base += `&schemata=${this.schemataSearch}`
        if(this.whenFilter) base += `&timeline=${this.whenFilter}`
        fetch(base)
            .then(r => r.json())
            .then(data => {
                isFiltering = true;
                actions = data;
            }).catch(err => ShowFeedback('error', 'Filter operation failed'))
    },

    clearFilter(){
        this.actionSearch = '';
        this.applicationSearch = '';
        this.schemataSearch = '';
        this.whenFilter = '';
        isFiltering = false;
        fetchAll();
    },

    checkDirty(){
        this.isFilterable = (
            this.actionSearch !== '' ||
            this.applicationSearch !== '' ||
            this.schemataSearch !== '' ||
            this.whenFilter !== ''
        );
        return this.isFilterable;
    }
}
{% endmacro %}


{% block easel %}
<section x-data="{{ controller('actions') }}">

    <!-- Preview Mode -->
    <template x-if="previewing">
        <div x-data="{ readOnlyIDE: null }" class="preview-layout">
            <!-- Top: back button + title -->
            <div class="page-content-scroll pb-0">
                <div class="d-flex align-items-center gap-3 mb-3">
                    <button class="btn btn-sm btn-outline-secondary d-inline-flex align-items-center gap-1"
                        @click="previewing = null">
                        <span class="material-icons" style="font-size: 16px;">arrow_back</span>
                        Back
                    </button>
                    <h1 class="page-title mb-0" x-text="previewing.action"></h1>
                    <span class="badge bg-secondary bg-opacity-10 text-secondary"
                        x-text="previewing.application"></span>
                </div>
            </div>

            <!-- Cards row filling remaining height -->
            <div class="preview-cards">
                <!-- Detail card -->
                <div class="detail-panel preview-detail-card">
                    <div class="detail-panel-header">
                        <h6 class="fw-bold mb-0">Details</h6>
                    </div>
                    <div class="detail-panel-body">
                        <div class="detail-field">
                            <span class="field-label">Application</span>
                            <span class="field-value" x-text="previewing.application"></span>
                        </div>
                        <div class="detail-field">
                            <span class="field-label">Created</span>
                            <span class="field-value" x-text="previewing.timestamped"></span>
                        </div>
                        <div class="detail-field">
                            <span class="field-label">Events</span>
                            <span class="field-value" x-text="`${previewing.successful || 0} / ${previewing.tally || 0}`"></span>
                        </div>
                        <div class="detail-field">
                            <span class="field-label">Subscribers</span>
                            <span class="field-value" x-text="previewing.subscribers || 0"></span>
                        </div>
                    </div>
                    <div class="detail-panel-footer">
                        <span class="text-xs text-muted-custom"
                            x-text="`${prettyJson(previewing.schemata || {}).split('\\n').length} lines · ${prettyJson(previewing.schemata || {}).length} chars`"></span>
                    </div>
                </div>

                <!-- Schema card filling remaining width + full height -->
                <div class="detail-panel preview-schema-card">
                    <div class="detail-panel-header">
                        <h6 class="fw-bold mb-0">JSON Schema</h6>
                        <button class="btn-action"
                            @click="navigator.clipboard.writeText(typeof previewing.schemata === 'string' ? previewing.schemata : prettyJson(previewing.schemata || {})); ShowFeedback('success', 'Copied to clipboard')">
                            <span class="material-icons">content_copy</span>
                            Copy
                        </button>
                    </div>
                    <div class="preview-editor-ace" x-init="() => {
                        readOnlyIDE = ace.edit($el);
                        readOnlyIDE.session.setMode('ace/mode/json');
                        readOnlyIDE.setTheme(darkMode ? 'ace/theme/one_dark' : 'ace/theme/chrome');
                        readOnlyIDE.setOptions({
                            readOnly: true,
                            fontSize: 13,
                            fontFamily: 'JetBrains Mono, SF Mono, Fira Code, monospace',
                            showPrintMargin: false,
                            highlightActiveLine: false,
                            highlightGutterLine: false,
                            showGutter: true,
                            displayIndentGuides: true,
                            tabSize: 2,
                            wrap: false
                        });
                        const val = typeof previewing.schemata === 'string'
                            ? previewing.schemata
                            : prettyJson(previewing.schemata || {});
                        readOnlyIDE.setValue(val);
                        readOnlyIDE.clearSelection();
                        readOnlyIDE.gotoLine(1);
                    }"></div>
                </div>
            </div>
        </div>
    </template>

    <!-- List Mode -->
    <template x-if="!previewing">
        <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">Actions</h1>
                        <p class="page-subtitle">Event type definitions and JSON schemas</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">bolt</span>
                        <input class="form-control" type="text" placeholder="Action name..." x-model="actionSearch"
                            style="width: 180px;">
                    </div>
                    <div class="input-icon">
                        <span class="material-icons">layers</span>
                        <input class="form-control" type="text" placeholder="Application..." x-model="applicationSearch"
                            style="width: 200px;">
                    </div>
                    <div class="input-icon">
                        <span class="material-icons">data_object</span>
                        <input class="form-control" type="text" placeholder="Search in schema..."
                            x-model="schemataSearch" style="width: 220px;">
                    </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: 25%">Action</th>
                                    <th style="width: 20%">Application</th>
                                    <th>Schema</th>
                                    <th style="width: 20%">Timestamp</th>
                                </tr>
                            </thead>
                            <tbody @refresher.window="refreshPage">
                                <template x-for="action in actions" :key="action.action">
                                    <tr class="cursor-pointer" @click="previewing = action">
                                        <td>
                                            <span class="fw-medium" x-text="action.action"></span>
                                        </td>
                                        <td>
                                            <span class="tag-id" x-text="action.application"></span>
                                        </td>
                                        <td>
                                            <span class="text-muted-custom text-sm"
                                                x-text="`${JSON.stringify(action.schemata || {}, null, 2).length} characters`"></span>
                                        </td>
                                        <td>
                                            <span class="text-muted-custom text-sm" x-text="action.timestamped"></span>
                                        </td>
                                    </tr>
                                </template>
                                <template x-if="actions.length === 0 && !loading">
                                    <tr>
                                        <td colspan="4">
                                            <div class="empty-state">
                                                <span class="material-icons">bolt</span>
                                                <p>No actions found</p>
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                    {{ pagination() }}
                </div>
            </div>

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


{% block wizard %}
<span x-data="{
    ide: null,
    applications: [],
    application: '',
    action: '',

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

    resetForm(){
        this.application = '';
        this.action = '';
        if(this.ide) this.ide.setValue('');
    },

    saveAction(){
        superpost('/v1/actions').send({
            application: this.application,
            schemata: this.ide.getValue(),
            action: this.action
        }).then(res => {
            ShowFeedback('success', 'Action created');
            this.resetForm();
            $dispatch('refresher');
            showModal = false;
        }).catch(err => {
            supertoast('error', err.response?.body?.error || 'Failed to create action');
        })
    }
}">
    <div class="modal-body">
        <div class="mb-3">
            <label class="form-label-sm">Action Name</label>
            <div class="input-group">
                <span class="input-group-text bg-transparent border-end-0">
                    <span class="material-icons text-muted" style="font-size: 18px;">bolt</span>
                </span>
                <input type="text" class="form-control border-start-0" placeholder="e.g. user.created"
                    x-model="action">
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label-sm">Application</label>
            <select class="form-select" x-model="application" x-init="fetchApplications" aria-label="Application">
                <option value="">Select Application...</option>
                <template x-for="app in applications">
                    <option :value="app.application" x-text="app.application"></option>
                </template>
            </select>
        </div>

        <div class="mb-0">
            <label class="form-label-sm">JSON Schema</label>
            <div id="schemator" style="height: 280px;" x-init="() => {
                ide = ace.edit($el);
                ide.session.setMode('ace/mode/json');
            }" @keydown.cmd.s.prevent="supertoast('info', 'Click Save to save this action')"></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="saveAction">
            <span class="material-icons" style="font-size: 16px;">save</span>
            Save Action
        </button>
    </div>
</span>
{% endblock %}
