/**
 * StatisticsTab Component
 * Displays statistics for SharePoint content
 */
Vue.component('statistics-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        },
        platformType: {
            type: String,
        },
        connection: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            currentNodeStats: null,
            allStats: null,
            loading: false,
            builtInTypes: [
                'Master Page Gallery',
                'Web Part Gallery',
                'Theme Gallery',
                'Style Library',
                'User Information List',
                'Site Pages',
                'Site Assets',
                'Site Collection Documents',
                'Site Collection Images',
                'Site Collection Workflow History',
                'Site Collection Workflow Tasks',
                'Workflow History',
                'Workflow Tasks',
                'Composed Looks',
                'List',
                'Document',
                'Folder',
                'Item'
            ],
            builtInChart: null,
            contentTypeChart: null,
            chartsInitialized: false,
            chartJsAvailable: false
        };
    },
    mounted() {
        console.log('StatisticsTab mounted');
        this.LoadAllStats();
        // Wait for the DOM to be ready and Chart.js to be loaded
        this.$nextTick(() => {
            this.checkChartJs();
        });
    },
    watch: {
        selectedNode: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    // Reset loading state when node changes
                    this.loading = true;
                    this.currentNodeStats = null;
                    this.$nextTick(() => {
                        this.UpdateNodeStats(newVal);
                    });
                } else {
                    this.currentNodeStats = null;
                    this.loading = false;
                }
            }
        },
        currentNodeStats: {
            handler(newVal) {
                if (newVal && this.chartJsAvailable) {
                    // Only render charts if we have data and Chart.js is available
                    this.$nextTick(() => {
                        this.renderCharts();
                    });
                }
            }
        }
    },
    methods: {
        checkChartJs() {
            console.log('Checking Chart.js availability');
            try {
                // Check if Chart is available as a global variable
                if (typeof window.Chart !== 'undefined') {
                    console.log('Chart.js is available');
                    this.chartJsAvailable = true;
                    if (this.currentNodeStats) {
                        this.renderCharts();
                    }
                } else {
                    console.log('Chart.js not found, retrying in 500ms');
                    setTimeout(() => this.checkChartJs(), 500);
                }
            } catch (e) {
                console.error('Error checking Chart.js:', e);
                setTimeout(() => this.checkChartJs(), 500);
            }
        },
        async LoadAllStats() {
            this.loading = true;
        },
        async UpdateNodeStats(node, forceRecalculate = false) {
            if (!this.connection) {
                console.error('No connection available for stats');
                this.loading = false;
                return;
            }
            
            console.log('Platform type:', this.platformType);
            console.log('Connection platform:', this.connection.platformType);
            
            // Loading state is set in the watcher for selectedNode
            try {
                // Add recalculate parameter for Sitecore platform
                const platformToUse = this.platformType || this.connection.platformType;
                const recalculateParam = forceRecalculate && platformToUse === 'Sitecore' ? '&recalculate=true' : '';
                const res = await fetch(`/api/ContentTree/GetNodeStats?platformType=${platformToUse}&id=${node.id}&connectionId=${this.connection.id}${recalculateParam}`);
                const json = await res.json();
                console.log('Received stats:', json);
                
                // Check if statistics are still being calculated
                if (json.calculating === true) {
                    this.currentNodeStats = json; // Use partial data if available
                    
                    // Try again after a delay
                    setTimeout(() => {
                        if (this.selectedNode && this.selectedNode.id === node.id) {
                            console.log('Stats calculation in progress, retrying...');
                            this.UpdateNodeStats(node);
                        }
                    }, 3000); // Poll every 3 seconds
                } else {
                    this.currentNodeStats = json;
                    this.loading = false;
                }
            } catch (error) {
                console.error('Error fetching node stats:', error);
                if (typeof Helpers !== 'undefined' && Helpers.showNotification) {
                    Helpers.showNotification('Error loading node statistics', 'error');
                }
                this.loading = false;
            }
        },
        formatDate(dateString) {
            return new Date(dateString).toLocaleString();
        },
        isBuiltInType(type) {
            return this.builtInTypes.includes(type);
        },
        getSortedContentTypes() {
            if (!this.currentNodeStats?.contentTypeCounts) return [];
            return Object.entries(this.currentNodeStats.contentTypeCounts)
                .sort((a, b) => b[1] - a[1]);
        },
        getSortedFileTypes() {
            if (!this.currentNodeStats?.fileTypeCounts) return [];
            return Object.entries(this.currentNodeStats.fileTypeCounts)
                .sort((a, b) => b[1] - a[1]);
        },
        renderCharts() {
            if (!this.currentNodeStats?.contentTypeCounts || typeof window.Chart === 'undefined') {
                console.log('Cannot render charts - missing data or Chart.js');
                return;
            }
            
            console.log('Rendering charts with data');

            // Destroy existing charts to prevent memory leaks
            if (this.builtInChart) {
                this.builtInChart.destroy();
                this.builtInChart = null;
            }
            
            if (this.contentTypeChart) {
                this.contentTypeChart.destroy();
                this.contentTypeChart = null;
            }

            // Calculate built-in vs non-built-in counts
            let builtInCount = 0;
            let nonBuiltInCount = 0;
            Object.entries(this.currentNodeStats.contentTypeCounts).forEach(([type, count]) => {
                if (this.isBuiltInType(type)) {
                    builtInCount += count;
                } else {
                    nonBuiltInCount += count;
                }
            });

            // Create charts in the next tick to ensure DOM is updated
            this.$nextTick(() => {
                // Built-in vs Non-built-in Chart
                var chartColors = ['#6384ff', '#34d399', '#fb923c', '#fbbf24', '#f87171'];

                const builtInCtx = document.getElementById('builtInChart');
                if (builtInCtx) {
                    try {
                        this.builtInChart = new window.Chart(builtInCtx, {
                            type: 'doughnut',
                            data: {
                                labels: ['Built-in', 'Custom'],
                                datasets: [{
                                    data: [builtInCount, nonBuiltInCount],
                                    backgroundColor: ['#6384ff', '#34d399'],
                                    borderWidth: 0,
                                    hoverOffset: 8
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                cutout: '60%',
                                plugins: {
                                    legend: {
                                        position: 'bottom',
                                        labels: { padding: 16, usePointStyle: true, font: { size: 12 } }
                                    },
                                    title: {
                                        display: true,
                                        text: 'Built-in vs Custom Content',
                                        font: { size: 14, weight: '600' },
                                        padding: { bottom: 16 }
                                    }
                                }
                            }
                        });
                    } catch (e) {
                        console.error('Error creating built-in chart:', e);
                    }
                }

                var topContentTypes = this.getSortedContentTypes().slice(0, 5);
                const contentTypeCtx = document.getElementById('contentTypeChart');
                if (contentTypeCtx) {
                    try {
                        this.contentTypeChart = new window.Chart(contentTypeCtx, {
                            type: 'doughnut',
                            data: {
                                labels: topContentTypes.map(function (x) { return x[0]; }),
                                datasets: [{
                                    data: topContentTypes.map(function (x) { return x[1]; }),
                                    backgroundColor: chartColors,
                                    borderWidth: 0,
                                    hoverOffset: 8
                                }]
                            },
                            options: {
                                responsive: true,
                                maintainAspectRatio: false,
                                cutout: '55%',
                                plugins: {
                                    legend: {
                                        position: 'bottom',
                                        labels: { padding: 16, usePointStyle: true, font: { size: 12 } }
                                    },
                                    title: {
                                        display: true,
                                        text: 'Top 5 Content Types',
                                        font: { size: 14, weight: '600' },
                                        padding: { bottom: 16 }
                                    }
                                }
                            }
                        });
                    } catch (e) {
                        console.error('Error creating content type chart:', e);
                    }
                }
            });
        }
    },
    template: `
        <div class="statistics-tab">
            <!-- Node-specific Statistics Section -->
            <div v-if="selectedNode">
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="card-title">{{selectedNode.name}}</h5>
                            <button 
                                v-if="platformType === 'Sitecore' || (connection && connection.platformType === 'Sitecore')" 
                                class="btn btn-sm btn-outline-primary" 
                                @click="UpdateNodeStats(selectedNode, true)"
                                :disabled="loading"
                            >
                                <span v-if="loading" class="spinner-border spinner-border-sm mr-1" role="status"></span>
                                Recalculate
                            </button>
                        </div>
                        <div v-if="loading && !currentNodeStats" class="text-center p-5">
                            <div class="spinner-border text-primary" role="status">
                                
                            </div>
                        </div>
                        <div v-else-if="currentNodeStats" class="mt-4">
                            <div v-if="currentNodeStats.calculating" class="alert alert-info">
                                <div class="d-flex align-items-center">
                                    <div class="spinner-border spinner-border-sm text-primary mr-2" role="status">
                                        <span class="sr-only">Calculating...</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Content Overview -->
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body text-center">
                                            <h3 class="card-title text-primary">{{currentNodeStats.totalItems}}</h3>
                                            <p class="card-text text-muted">Total Items</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body text-center">
                                            <h3 class="card-title text-primary">{{currentNodeStats.directChildren}}</h3>
                                            <p class="card-text text-muted">Direct Children</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body text-center">
                                            <h3 class="card-title text-primary">{{currentNodeStats.totalDescendants}}</h3>
                                            <p class="card-text text-muted">Total Descendants</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body text-center">
                                            <h3 class="card-title text-primary">{{currentNodeStats.maxDepth}}</h3>
                                            <p class="card-text text-muted">Maximum Depth</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Charts -->
                            <div v-if="chartJsAvailable && !currentNodeStats.calculating" class="row mt-4">
                                <div class="col-md-6">
                                    <div class="chart-container">
                                        <canvas id="builtInChart" width="400" height="400"></canvas>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="chart-container">
                                        <canvas id="contentTypeChart" width="400" height="400"></canvas>
                                    </div>
                                </div>
                            </div>
                            <div v-else-if="currentNodeStats.calculating" class="alert alert-light text-center">
                                <p>Charts will be available once statistics calculation is complete</p>
                            </div>
                            <div v-else class="alert alert-warning">
                                Charts are not available. Please ensure Chart.js is loaded.
                            </div>

                            <!-- Content Types -->
                            <div v-if="currentNodeStats.contentTypeCounts && Object.keys(currentNodeStats.contentTypeCounts).length > 0" class="mb-4 mt-4">
                                <h6>Content Types</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm table-hover">
                                        <thead>
                                            <tr>
                                                <th>Type</th>
                                                <th class="text-right">Count</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr v-for="[type, count] in getSortedContentTypes()" :key="type" :class="{ 'built-in': isBuiltInType(type) }">
                                                <td>
                                                    <span v-if="isBuiltInType(type)" class="badge badge-outline ml-5 text-black-50 text-primary">Built-in</span>
                                                    {{type}}
                                                </td>
                                                <td class="text-right">{{count}}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div v-else-if="currentNodeStats.calculating" class="mb-4 mt-4">
                                <h6>Content Types</h6>
                                <p class="text-muted">Content type information will be available once calculation is complete</p>
                            </div>

                            <!-- File Types -->
                            <div v-if="currentNodeStats.fileTypeCounts && Object.keys(currentNodeStats.fileTypeCounts).length > 0" class="mb-4">
                                <h6>File Types</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm table-hover">
                                        <thead>
                                            <tr>
                                                <th>Type</th>
                                                <th class="text-right">Count</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr v-for="[type, count] in getSortedFileTypes()" :key="type">
                                                <td>{{type}}</td>
                                                <td class="text-right">{{count}}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div v-else-if="currentNodeStats.calculating" class="mb-4">
                                <h6>File Types</h6>
                                <p class="text-muted">File type information will be available once calculation is complete</p>
                            </div>

                            <!-- Last Updated -->
                            <div class="text-muted small">
                                Last Updated: {{formatDate(currentNodeStats.lastUpdated)}}
                            </div>
                        </div>
                        <div v-else class="alert alert-info">
                            Loading node statistics...
                        </div>
                    </div>
                </div>
            </div>
            <div v-else class="alert alert-info">
                Select a node from the tree to view its specific statistics.
            </div>
        </div>
    `
}); 