<template>
    <div class="analytics-dashboard">
        <!-- Заголовок с кнопкой сбора аналитики -->
        <div class="card mb-4">
            <div class="card-header">
                <h5>Аналитика SMM системы</h5>
                <Button icon="pi pi-refresh" label="Собрать аналитику" @click="collectAnalytics" :loading="collecting" class="p-button-info" />
            </div>
        </div>

        <!-- Статистические карточки -->
        <div class="grid">
            <div class="col-12 md:col-6 lg:col-3">
                <div class="card stat-card">
                    <div class="stat-content">
                        <div class="stat-icon">
                            <i class="pi pi-chart-line text-blue-500"></i>
                        </div>
                        <div class="stat-info">
                            <h6>Кампании</h6>
                            <h3>{{ systemStats.campaigns?.total || 0 }}</h3>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12 md:col-6 lg:col-3">
                <div class="card stat-card">
                    <div class="stat-content">
                        <div class="stat-icon">
                            <i class="pi pi-broadcast-tower text-green-500"></i>
                        </div>
                        <div class="stat-info">
                            <h6>Каналы</h6>
                            <h3>{{ systemStats.channels?.total || 0 }}</h3>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12 md:col-6 lg:col-3">
                <div class="card stat-card">
                    <div class="stat-content">
                        <div class="stat-icon">
                            <i class="pi pi-file text-orange-500"></i>
                        </div>
                        <div class="stat-info">
                            <h6>Контент</h6>
                            <h3>{{ systemStats.content?.total || 0 }}</h3>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12 md:col-6 lg:col-3">
                <div class="card stat-card">
                    <div class="stat-content">
                        <div class="stat-icon">
                            <i class="pi pi-send text-purple-500"></i>
                        </div>
                        <div class="stat-info">
                            <h6>Опубликовано</h6>
                            <h3>{{ publishingStats.totalPublished || 0 }}</h3>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Детальная статистика -->
        <div class="grid">
            <!-- Статистика кампаний -->
            <div class="col-12 lg:col-6">
                <div class="card">
                    <div class="card-header">
                        <h6>Статистика кампаний</h6>
                    </div>
                    <div class="card-content">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <span class="stat-label">Активные:</span>
                                <span class="stat-value text-green-600">{{ systemStats.campaigns?.activeCampaigns || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Завершенные:</span>
                                <span class="stat-value text-blue-600">{{ systemStats.campaigns?.completedCampaigns || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Запланированные:</span>
                                <span class="stat-value text-orange-600">{{ systemStats.campaigns?.plannedCampaigns || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Общий бюджет:</span>
                                <span class="stat-value text-purple-600">{{ formatCurrency(systemStats.campaigns?.totalBudget || 0) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Статистика каналов -->
            <div class="col-12 lg:col-6">
                <div class="card">
                    <div class="card-header">
                        <h6>Статистика каналов</h6>
                    </div>
                    <div class="card-content">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <span class="stat-label">Активные:</span>
                                <span class="stat-value text-green-600">{{ systemStats.channels?.activeChannels || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Неактивные:</span>
                                <span class="stat-value text-red-600">{{ systemStats.channels?.inactiveChannels || 0 }}</span>
                            </div>
                            <div class="stat-item" v-for="(count, type) in systemStats.channels?.byType" :key="type">
                                <span class="stat-label">{{ getChannelTypeLabel(type) }}:</span>
                                <span class="stat-value">{{ count }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Статистика контента -->
            <div class="col-12 lg:col-6">
                <div class="card">
                    <div class="card-header">
                        <h6>Статистика контента</h6>
                    </div>
                    <div class="card-content">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <span class="stat-label">Ожидает одобрения:</span>
                                <span class="stat-value text-orange-600">{{ systemStats.content?.pendingApproval || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Одобрен:</span>
                                <span class="stat-value text-blue-600">{{ systemStats.content?.approved || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Опубликован:</span>
                                <span class="stat-value text-green-600">{{ systemStats.content?.published || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Ошибки:</span>
                                <span class="stat-value text-red-600">{{ systemStats.content?.failed || 0 }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Статистика публикаций -->
            <div class="col-12 lg:col-6">
                <div class="card">
                    <div class="card-header">
                        <h6>Статистика публикаций</h6>
                    </div>
                    <div class="card-content">
                        <div class="stats-grid">
                            <div class="stat-item">
                                <span class="stat-label">Опубликовано:</span>
                                <span class="stat-value text-green-600">{{ publishingStats.totalPublished || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Всего контента:</span>
                                <span class="stat-value">{{ publishingStats.totalContent || 0 }}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">Процент публикации:</span>
                                <span class="stat-value text-blue-600">{{ publishingStats.publishingRate?.toFixed(1) || 0 }}%</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Время последнего обновления -->
        <div class="card mt-4">
            <div class="card-content text-center">
                <small class="text-600"> Последнее обновление: {{ formatDateTime(systemStats.timestamp) }} </small>
            </div>
        </div>
    </div>
</template>

<script>
import AnalyticsService from '@/service/AnalyticsService.js';
import { ChannelType } from '@/types/smm.js';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref } from 'vue';

export default {
    name: 'AnalyticsDashboard',
    setup() {
        const toast = useToast();

        // Reactive data
        const systemStats = ref({});
        const publishingStats = ref({});
        const collecting = ref(false);

        // Methods
        const loadAnalytics = async () => {
            try {
                const [systemStatsData, publishingStatsData] = await Promise.all([AnalyticsService.getSystemStats(), AnalyticsService.getPublishingStats()]);

                systemStats.value = systemStatsData;
                publishingStats.value = publishingStatsData;
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось загрузить аналитику: ' + error.message,
                    life: 3000
                });
            }
        };

        const collectAnalytics = async () => {
            collecting.value = true;
            try {
                await AnalyticsService.collectAnalytics();
                toast.add({
                    severity: 'success',
                    summary: 'Успех',
                    detail: 'Сбор аналитики запущен',
                    life: 3000
                });
                // Перезагружаем данные после сбора
                setTimeout(() => {
                    loadAnalytics();
                }, 2000);
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось запустить сбор аналитики: ' + error.message,
                    life: 3000
                });
            } finally {
                collecting.value = false;
            }
        };

        const formatCurrency = (value) => {
            return new Intl.NumberFormat('ru-RU', {
                style: 'currency',
                currency: 'KZT'
            }).format(value || 0);
        };

        const formatDateTime = (dateString) => {
            if (!dateString) return 'Не определено';
            return new Date(dateString).toLocaleString('ru-RU', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        };

        const getChannelTypeLabel = (type) => {
            const labels = {
                [ChannelType.TELEGRAM]: 'Telegram',
                [ChannelType.VK]: 'VK',
                [ChannelType.INSTAGRAM]: 'Instagram'
            };
            return labels[type] || type;
        };

        // Lifecycle
        onMounted(() => {
            loadAnalytics();
        });

        return {
            systemStats,
            publishingStats,
            collecting,
            loadAnalytics,
            collectAnalytics,
            formatCurrency,
            formatDateTime,
            getChannelTypeLabel
        };
    }
};
</script>

<style scoped>
.analytics-dashboard {
    padding: 1rem;
}

.stat-card {
    background: var(--surface-card);
    border-radius: 12px;
    box-shadow:
        0 1px 3px rgba(0, 0, 0, 0.12),
        0 1px 2px rgba(0, 0, 0, 0.24);
    transition: transform 0.2s ease;
}

.stat-card:hover {
    transform: translateY(-2px);
}

.stat-content {
    display: flex;
    align-items: center;
    padding: 1.5rem;
}

.stat-icon {
    font-size: 2rem;
    margin-right: 1rem;
}

.stat-info h6 {
    margin: 0 0 0.5rem 0;
    color: var(--text-color-secondary);
    font-size: 0.875rem;
    font-weight: 500;
}

.stat-info h3 {
    margin: 0;
    font-size: 2rem;
    font-weight: 700;
    color: var(--text-color);
}

.card {
    background: var(--surface-card);
    border-radius: 12px;
    box-shadow:
        0 1px 3px rgba(0, 0, 0, 0.12),
        0 1px 2px rgba(0, 0, 0, 0.24);
}

.card-header {
    padding: 1.5rem;
    border-bottom: 1px solid var(--surface-border);
}

.card-header h6 {
    margin: 0;
    font-size: 1.125rem;
    font-weight: 600;
    color: var(--text-color);
}

.card-content {
    padding: 1.5rem;
}

.stats-grid {
    display: grid;
    gap: 1rem;
}

.stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--surface-border);
}

.stat-item:last-child {
    border-bottom: none;
}

.stat-label {
    font-weight: 500;
    color: var(--text-color-secondary);
}

.stat-value {
    font-weight: 600;
    font-size: 1.125rem;
}

.text-600 {
    color: var(--text-color-secondary);
}

.text-center {
    text-align: center;
}

.mb-4 {
    margin-bottom: 1rem;
}

.mt-4 {
    margin-top: 1rem;
}
</style>
