{include file="./index_top.tpl"}

<style>
    .gpt-integrations {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 18px;
    }

    .gpt-integrations__loading,
    .gpt-integrations__empty {
        color: #666;
        text-align: center;
    }

    .gpt-integrations__list {
        list-style: none;
        margin: 0 auto;
        padding: 0;
        display: inline-flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 14px;
        width: auto;
        max-width: 100%;
    }

    .gpt-integrations__item {
        display: block;
        width: auto;
    }

    .gpt-integrations__row {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        gap: 5px;
        min-height: 20px;
        text-align: left;
        white-space: nowrap;
    }

    .gpt-integrations__link {
        display: inline-block;
        font-size: 13px;
        font-weight: 700;
        text-decoration: none;
        line-height: 16px;
        text-align: left;
    }

    .gpt-integrations__link:hover {
        text-decoration: underline;
    }

    .gpt-switch {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 16px;
        flex: 0 0 30px;
        cursor: pointer;
        margin-right: 4px;
    }

    .gpt-switch__track {
        display: block;
        width: 30px;
        height: 11px;
        border-radius: 5px;
        background-color: #D0D0D0;
        position: relative;
        transition: background-color 0.3s ease;
    }

    .gpt-switch__track.active {
        background-color: #AD83BE;
    }

    .gpt-switch__circle {
        display: block;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background-color: #989898;
        position: absolute;
        top: -2px;
        left: -2px;
        transition: left 0.3s ease, background-color 0.3s ease;
    }

    .gpt-switch__circle.active {
        background-color: #5A087E;
        left: 14px;
    }

    .gpt-switch.disabled {
        opacity: 0.6;
        cursor: wait;
    }

    .gpt-action-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 16px;
        height: 16px;
        padding: 0;
        margin: 0;
        border: 0;
        background: transparent;
        cursor: pointer;
        text-decoration: none;
        flex: 0 0 16px;
    }

    .gpt-action-btn img,
    .gpt-action-btn svg {
        display: block;
        width: 16px;
        height: 16px;
    }

    .gpt-integrations__meta {
        display: flex;
        gap: 7px;
        margin-left: 5px;
        color: #808080;
        font-size: 13px;
        line-height: 18.6px;
    }

    .gpt-integrations__meta span {
        white-space: nowrap;
        font-style: italic;
    }
</style>

<div align="center">
    <br>
    Интеграции GPT "{$name_table}"
    <br><br>

    {if $table_id}
        {include file="./conf_nav.tpl"}
    {/if}

    {if $is_gpt_active}
        <div class="gpt-integrations">
            <div id="gpt_integrations_loading" class="gpt-integrations__loading">Загрузка...</div>
            <div id="gpt_integrations_empty" class="gpt-integrations__empty" style="display:none;">Нет GPT-интеграций для
                этой таблицы</div>
            <ul id="gpt_integrations_list" class="gpt-integrations__list" style="display:none;"></ul>
        </div>

        <br><br>
        <a href="edit_modules.php?extension=cbext.clientbase.clientbase_gpt#1/add" target="_blank" class="btn btn-default">
            Добавить интеграцию
        </a>

        <br><br>
    {else}  
        <div style="text-align: center; color: #666; font-size: 14px; padding: 20px 0;">
            {$gpt_error_msg nofilter}
        </div>
        <br><br>
    {/if}
    

    {if $table_id}
        <a href="{if $back_url}{$back_url}{else}edit_tabrep.php?cat={$cat_id}{/if}">{$lang.return_to_tables}</a> |
        <a href="fields.php?table={$table_id}" target="_blank">{$lang.view_table}</a>
    {else}
        <a href="edit_add.php">{$lang.return_to_add_settings}</a>
    {/if}

    <br><br>
</div>

{if $is_gpt_active}
<script>
    function makePreloader() {
        const overlay = `<div class='overlay'></div>`;
        const preloader = `<div class="preloader__block" style="z-index: 10000000;">
                                        <div class="preloader">
                                            <div class="lds-css ng-scope">
                                                <div style="width:100%;height:100%" class="lds-ellipsis">
                                                    <div>
                                                        <div></div>
                                                    </div>
                                                    <div>
                                                        <div></div>
                                                    </div>
                                                    <div>
                                                        <div></div>
                                                    </div>
                                                    <div>
                                                        <div></div>
                                                    </div>
                                                    <div>
                                                        <div></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>`;
        $('body').append(overlay);
        $('body').append(preloader);
    }

    function destroyPreloader() {
        $('.overlay').remove();
        $('.preloader__block').remove();
    }
    (function() {
        const integrationIds = {$table_integration_ids_json nofilter} || [];
        const list = document.getElementById('gpt_integrations_list');
        const loading = document.getElementById('gpt_integrations_loading');
        const empty = document.getElementById('gpt_integrations_empty');

        loadGptSettings()
            .then(data => {
                const connectors = ((((data || {}).data || {}).attributes || {}).value || {}).connectors || [];

                const filtered = connectors.filter(item => {
                    const connectorId = parseInt(item.id || 0, 10);
                    return integrationIds.includes(connectorId);
                });

                loading.style.display = 'none';

                if (!filtered.length) {
                    empty.style.display = '';
                    destroyPreloader();
                    return;
                }

                list.innerHTML = '';

                filtered.forEach(item => {
                    const li = document.createElement('li');
                    li.className = 'gpt-integrations__item';

                    const integrationUrl =
                        'edit_modules.php?extension=cbext.clientbase.clientbase_gpt#1/' +
                        encodeURIComponent(item.id);
                    const isEnabled = parseInt(item.disabled || 0, 10) === 0;

                    const provider = getProviderValue(item);
                    const model = getModelValue(item);

                    li.innerHTML =
                        '<div class="gpt-integrations__row">' +
                        '<button class="gpt-action-btn gpt-delete-btn" data-id="' + parseInt(item.id,
                            10) + '" title="Удалить" type="button">' +
                        '<img src="images/b_drop.png">' +
                        '</button>' +
                        '<span class="gpt-switch" data-id="' + parseInt(item.id, 10) + '">' +
                        '<span class="gpt-switch__track' + (isEnabled ? ' active' : '') + '">' +
                        '<span class="gpt-switch__circle' + (isEnabled ? ' active' : '') + '"></span>' +
                        '</span>' +
                        '</span>' +
                        '<a class="gpt-integrations__link" href="' + integrationUrl +
                        '" target="_blank">' + escapeHtml(item.name || '') + '</a>' +
                        ((provider || model) ?
                            '<div class="gpt-integrations__meta">' +
                            (provider ? '<span>' + escapeHtml(provider) + '</span>' : '') +
                            (model ? '<span>' + escapeHtml(model) + '</span>' : '') +
                            '</div>' :
                            '') +
                        '</div>';

                    list.appendChild(li);
                });

                bindSwitchers();
                bindDeleteButtons();
                list.style.display = '';
                destroyPreloader();
            })
            .catch((error) => {
                destroyPreloader();
                loading.innerHTML = '<span style="color:red;">Не удалось загрузить GPT-интеграции: ' +
                    escapeHtml(error.message) + '</span>';
            });

        function bindSwitchers() {
            document.querySelectorAll('.gpt-switch').forEach(function(switchEl) {
                switchEl.addEventListener('click', async function(e) {
                    e.preventDefault();

                    if (switchEl.classList.contains('disabled')) {
                        return;
                    }

                    const connectorId = parseInt(switchEl.getAttribute('data-id'), 10);
                    const track = switchEl.querySelector('.gpt-switch__track');
                    const circle = switchEl.querySelector('.gpt-switch__circle');
                    const newEnabledState = !track.classList.contains('active');

                    switchEl.classList.add('disabled');
                    makePreloader();

                    try {
                        await toggleConnectorState(connectorId, newEnabledState);
                        track.classList.toggle('active', newEnabledState);
                        circle.classList.toggle('active', newEnabledState);
                    } catch (error) {
                        alert('Не удалось изменить статус интеграции: ' + error.message);
                    } finally {
                        destroyPreloader();
                        switchEl.classList.remove('disabled');
                    }
                });
            });
        }

        function bindDeleteButtons() {
            document.querySelectorAll('.gpt-delete-btn').forEach(function(btn) {
                btn.addEventListener('click', async function(e) {
                    e.preventDefault();
                    const connectorId = parseInt(btn.getAttribute('data-id'), 10);
                    makePreloader();
                    try {
                        await deleteConnector(connectorId);
                        location.reload();
                    } catch (error) {
                        alert('Не удалось удалить интеграцию: ' + error.message);
                    } finally {
                        destroyPreloader();
                    }
                });
            });
        }

        function escapeHtml(value) {
            return String(value)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function getMetaValue(rowData, params) {
            const list = Array.isArray(params) ? params : [params];
            for (const param of list) {
                const value =
                    rowData['external_action_params_param[' + param + ']'] ||
                    ((rowData.external_action_params || {})['param[' + param + ']']) ||
                    '';
                if (value) {
                    return value;
                }
            }
            return '';
        }

        function getProviderValue(rowData) {
            const provider = getMetaValue(rowData, 'ai_provider');
            const labels = {
                openai: 'OpenAI',
                yandex: 'Yandex'
            };
            return labels[provider] || provider;
        }

        function getModelValue(rowData) {
            return getMetaValue(rowData, [
                'text_model',
                'model',
                'vision_model',
                'image_model',
                'transcribe_model'
            ]);
        }
    })();

    async function loadGptSettings() {
        const response = await fetch('api/dev/settings/cbext.clientbase.clientbase_gpt', {
            credentials: 'same-origin',
            headers: {
                'content-type': 'application/vnd.api+json',
                'x-auth-token': '{$token|escape:"javascript"}'
            }
        });

        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }

        return response.json();
    }

    async function saveGptSettings(value) {
        const response = await fetch('api/dev/settings/cbext.clientbase.clientbase_gpt', {
            method: 'PATCH',
            credentials: 'same-origin',
            headers: {
                'content-type': 'application/vnd.api+json',
                'x-auth-token': '{$token|escape:"javascript"}'
            },
            body: JSON.stringify({
                data: {
                    type: 'settings',
                    id: 'cbext.clientbase.clientbase_gpt',
                    attributes: {
                        value: value
                    }
                }
            })
        });

        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }

        return response.json();
    }

    async function toggleConnectorState(connectorId, enabled) {
        const settings = await loadGptSettings();
        const value = (((settings || {}).data || {}).attributes || {}).value || {};
        const connectors = Array.isArray(value.connectors) ? value.connectors : [];

        const connector = connectors.find(item => parseInt(item.id, 10) === parseInt(connectorId, 10));
        if (!connector) {
            throw new Error('Интеграция не найдена');
        }

        connector.disabled = enabled ? 0 : 1;

        await saveGptSettings(value);
    }

    async function deleteConnector(connectorId) {
        const settings = await loadGptSettings();
        const value = (((settings || {}).data || {}).attributes || {}).value || {};
        const connectors = Array.isArray(value.connectors) ? value.connectors : [];
        value.connectors = connectors.filter(item => parseInt(item.id, 10) !== parseInt(connectorId, 10));
        await saveGptSettings(value);
    }
</script>
{/if}