/**
 * Integrations — Weather, Home Assistant, MQTT, Game integration sources.
 * Extracted from streams.ts to a dedicated top-level tab.
 */

import {
    _cachedWeatherSources, _cachedHASources, _cachedMQTTSources,
    _cachedGameIntegrations, _cachedGameAdapters,
    weatherSourcesCache, haSourcesCache, mqttSourcesCache,
    gameIntegrationsCache, gameAdaptersCache,
    apiKey,
} from '../core/state.ts';
import { t } from '../core/i18n.ts';
import { CardSection } from '../core/card-sections.ts';
import { TreeNav } from '../core/tree-nav.ts';
import { updateSubTabHash } from './tabs.ts';
import { getActiveSubTab, setActiveSubTab } from '../core/tab-registry.ts';
import { fetchWithAuth } from '../core/api.ts';
import { showToast, setTabRefreshing } from '../core/ui.ts';
import { createWeatherSourceCard, initWeatherSourceDelegation } from './weather-sources.ts';
import { createHASourceCard, initHASourceDelegation } from './home-assistant-sources.ts';
import { createMQTTSourceCard, initMQTTSourceDelegation } from './mqtt-sources.ts';
import { createGameIntegrationCard, csGameIntegrations } from './game-integration.ts';
import { ICON_GAMEPAD, ICON_TRASH, ICON_HELP } from '../core/icons.ts';
import * as P from '../core/icon-paths.ts';

// ── Bulk action handlers ──

function _bulkDeleteFactory(endpoint: string, cache: any, toast: string) {
    return async (ids: string[]) => {
        const results = await Promise.allSettled(ids.map(id =>
            fetchWithAuth(`/${endpoint}/${id}`, { method: 'DELETE' })
        ));
        const failed = results.filter(r => r.status === 'rejected' || ((r as any).value && !(r as any).value.ok)).length;
        if (failed) showToast(`${ids.length - failed}/${ids.length} deleted`, 'warning');
        else showToast(t(toast), 'success');
        cache.invalidate();
        await loadIntegrations();
    };
}

const _weatherSourceDeleteAction = [{ key: 'delete', labelKey: 'bulk.delete', icon: ICON_TRASH, style: 'danger', confirm: 'bulk.confirm_delete', handler: _bulkDeleteFactory('weather-sources', weatherSourcesCache, 'weather_source.deleted') }];
const _haSourceDeleteAction = [{ key: 'delete', labelKey: 'bulk.delete', icon: ICON_TRASH, style: 'danger', confirm: 'bulk.confirm_delete', handler: _bulkDeleteFactory('home-assistant/sources', haSourcesCache, 'ha_source.deleted') }];
const _mqttSourceDeleteAction = [{ key: 'delete', labelKey: 'bulk.delete', icon: ICON_TRASH, style: 'danger', confirm: 'bulk.confirm_delete', handler: _bulkDeleteFactory('mqtt/sources', mqttSourcesCache, 'mqtt_source.deleted') }];

// ── Card section instances ──

const csWeatherSources = new CardSection('weather-sources', { titleKey: 'weather_source.group.title', gridClass: 'templates-grid', addCardOnclick: "showWeatherSourceModal()", keyAttr: 'data-id', emptyKey: 'section.empty.weather_sources', bulkActions: _weatherSourceDeleteAction });
const csHASources = new CardSection('ha-sources', { titleKey: 'ha_source.group.title', gridClass: 'templates-grid', addCardOnclick: "showHASourceModal()", keyAttr: 'data-id', emptyKey: 'section.empty.ha_sources', bulkActions: _haSourceDeleteAction });
const csMQTTSources = new CardSection('mqtt-sources', { titleKey: 'mqtt_source.group.title', gridClass: 'templates-grid', addCardOnclick: "showMQTTSourceModal()", keyAttr: 'data-id', emptyKey: 'section.empty.mqtt_sources', bulkActions: _mqttSourceDeleteAction });

// Re-render integrations when language changes
document.addEventListener('languageChanged', () => { if (apiKey) loadIntegrations(); });

// ── Loading state ──

let _integrationsLoading = false;

// ── Tree navigation ──

let _integrationsTreeTriggered = false;

const _integrationsTree = new TreeNav('integrations-tree-nav', {
    onSelect: (key) => {
        _integrationsTreeTriggered = true;
        switchIntegrationTab(key);
        _integrationsTreeTriggered = false;
    }
});

// ── Tab switching ──

export function switchIntegrationTab(tabKey: string) {
    document.querySelectorAll('.stream-tab-panel[id^="integration-tab-"]').forEach(panel =>
        panel.classList.toggle('active', panel.id === `integration-tab-${tabKey}`)
    );
    setActiveSubTab('integrations', tabKey);
    updateSubTabHash('integrations', tabKey);
    if (!_integrationsTreeTriggered) {
        _integrationsTree.setActive(tabKey);
    }
}

// ── Tab-to-section mapping ──

const _integrationSectionMap: Record<string, CardSection[]> = {
    weather: [csWeatherSources],
    home_assistant: [csHASources],
    mqtt: [csMQTTSources],
    game: [csGameIntegrations],
};

// ── Load integrations ──

export async function loadIntegrations() {
    if (_integrationsLoading) return;
    _integrationsLoading = true;
    if (!csWeatherSources.isMounted()) setTabRefreshing('integrations-list', true);
    try {
        await Promise.all([
            weatherSourcesCache.fetch(),
            haSourcesCache.fetch(),
            mqttSourcesCache.fetch(),
            gameIntegrationsCache.fetch(),
            gameAdaptersCache.fetch(),
        ]);
        renderIntegrationsList();
    } catch (error: any) {
        if (error.isAuth) return;
        console.error('Error loading integrations:', error);
        document.getElementById('integrations-list')!.innerHTML = `
            <div class="error-message">${t('streams.error.load')}: ${error.message}</div>
        `;
    } finally {
        _integrationsLoading = false;
        setTabRefreshing('integrations-list', false);
    }
}

// ── Render ──

function renderIntegrationsList() {
    const container = document.getElementById('integrations-list')!;
    const activeTab = getActiveSubTab('integrations')!;

    const tabs = [
        { key: 'weather', icon: `<svg class="icon" viewBox="0 0 24 24">${P.cloudSun}</svg>`, titleKey: 'streams.group.weather', count: _cachedWeatherSources.length },
        { key: 'home_assistant', icon: `<svg class="icon" viewBox="0 0 24 24">${P.home}</svg>`, titleKey: 'streams.group.home_assistant', count: _cachedHASources.length },
        { key: 'mqtt', icon: `<svg class="icon" viewBox="0 0 24 24">${P.radio}</svg>`, titleKey: 'streams.group.mqtt', count: _cachedMQTTSources.length },
        { key: 'game', icon: ICON_GAMEPAD, titleKey: 'streams.group.game', count: _cachedGameIntegrations.length },
    ];

    // Build tree navigation structure
    const treeGroups = [
        { key: 'weather', titleKey: 'streams.group.weather', icon: `<svg class="icon" viewBox="0 0 24 24">${P.cloudSun}</svg>`, count: _cachedWeatherSources.length },
        { key: 'home_assistant', titleKey: 'streams.group.home_assistant', icon: `<svg class="icon" viewBox="0 0 24 24">${P.home}</svg>`, count: _cachedHASources.length },
        { key: 'mqtt', titleKey: 'streams.group.mqtt', icon: `<svg class="icon" viewBox="0 0 24 24">${P.radio}</svg>`, count: _cachedMQTTSources.length },
        { key: 'game', titleKey: 'streams.group.game', icon: ICON_GAMEPAD, count: _cachedGameIntegrations.length },
    ];

    // Build card items
    const weatherSourceItems = csWeatherSources.applySortOrder(_cachedWeatherSources.map(s => ({ key: s.id, html: createWeatherSourceCard(s) })));
    const haSourceItems = csHASources.applySortOrder(_cachedHASources.map(s => ({ key: s.id, html: createHASourceCard(s) })));
    const mqttSourceItems = csMQTTSources.applySortOrder(_cachedMQTTSources.map(s => ({ key: s.id, html: createMQTTSourceCard(s) })));
    const gameIntegrationItems = csGameIntegrations.applySortOrder(_cachedGameIntegrations.map(g => ({ key: g.id, html: createGameIntegrationCard(g) })));

    if (csWeatherSources.isMounted()) {
        // Incremental update: reconcile cards in-place
        _integrationsTree.updateCounts({
            weather: _cachedWeatherSources.length,
            home_assistant: _cachedHASources.length,
            mqtt: _cachedMQTTSources.length,
            game: _cachedGameIntegrations.length,
        });
        csWeatherSources.reconcile(weatherSourceItems);
        csHASources.reconcile(haSourceItems);
        csMQTTSources.reconcile(mqttSourceItems);
        csGameIntegrations.reconcile(gameIntegrationItems);
    } else {
        // First render: build full HTML
        const panels = tabs.map(tab => {
            let panelContent = '';
            if (tab.key === 'weather') panelContent = csWeatherSources.render(weatherSourceItems);
            else if (tab.key === 'home_assistant') panelContent = csHASources.render(haSourceItems);
            else if (tab.key === 'mqtt') panelContent = csMQTTSources.render(mqttSourceItems);
            else if (tab.key === 'game') panelContent = csGameIntegrations.render(gameIntegrationItems);
            return `<div class="stream-tab-panel${tab.key === activeTab ? ' active' : ''}" id="integration-tab-${tab.key}">${panelContent}</div>`;
        }).join('');

        container.innerHTML = panels;
        CardSection.bindAll([csWeatherSources, csHASources, csMQTTSources, csGameIntegrations]);

        // Event delegation for card actions
        initWeatherSourceDelegation(container);
        initHASourceDelegation(container);
        initMQTTSourceDelegation(container);

        // Render tree sidebar with tutorial trigger button
        _integrationsTree.setExtraHtml(`<button class="tutorial-trigger-btn" onclick="startIntegrationsTutorial()" data-i18n-title="tour.restart" title="${t('tour.restart')}">${ICON_HELP}</button>`);
        _integrationsTree.update(treeGroups, activeTab);
        _integrationsTree.observeSections('integrations-list', {
            'weather-sources': 'weather',
            'ha-sources': 'home_assistant',
            'mqtt-sources': 'mqtt',
            'game-integrations': 'game',
        });
    }
}
