<template>
    <div class="card">
        <div class="flex justify-content-between align-items-center mb-4">
            <h1 class="text-2xl font-semibold m-0">Статистика новостей</h1>
            <Button icon="pi pi-refresh" label="Обновить" @click="loadData" :loading="loading" severity="secondary" />
        </div>

        <!-- Общая статистика -->
        <div class="grid mb-4">
            <div class="col-12 md:col-3">
                <div class="card bg-blue-50 border-blue-200">
                    <div class="flex align-items-center">
                        <i class="pi pi-align-left text-blue-500 text-3xl mr-3"></i>
                        <div>
                            <div class="text-sm text-blue-600">Всего новостей</div>
                            <div class="text-2xl font-bold text-blue-900">{{ stats.totalItems || 0 }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 md:col-3">
                <div class="card bg-green-50 border-green-200">
                    <div class="flex align-items-center">
                        <i class="pi pi-calendar text-green-500 text-3xl mr-3"></i>
                        <div>
                            <div class="text-sm text-green-600">Последнее обновление</div>
                            <div class="text-sm font-semibold text-green-900">{{ formatDate(stats.lastUpdate) }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 md:col-3">
                <div class="card bg-orange-50 border-orange-200">
                    <div class="flex align-items-center">
                        <i class="pi pi-database text-orange-500 text-3xl mr-3"></i>
                        <div>
                            <div class="text-sm text-orange-600">Источников</div>
                            <div class="text-2xl font-bold text-orange-900">{{ sourceCount }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 md:col-3">
                <div class="card bg-purple-50 border-purple-200">
                    <div class="flex align-items-center">
                        <i class="pi pi-chart-line text-purple-500 text-3xl mr-3"></i>
                        <div>
                            <div class="text-sm text-purple-600">Среднее на источник</div>
                            <div class="text-2xl font-bold text-purple-900">{{ averagePerSource }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Статус системы -->
        <div class="grid mb-4">
            <div class="col-12 md:col-6">
                <Card>
                    <template #title>
                        <div class="flex align-items-center">
                            <i class="pi pi-cog mr-2"></i>
                            Статус сервиса
                        </div>
                    </template>
                    <template #content>
                        <div v-if="healthLoading" class="text-center py-3">
                            <ProgressSpinner size="30" />
                        </div>
                        <div v-else-if="health" class="space-y-3">
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Сервис:</span>
                                <Tag :value="health.status" :severity="health.status === 'UP' ? 'success' : 'danger'" />
                            </div>
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Название:</span>
                                <span>{{ health.service }}</span>
                            </div>
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Планировщик:</span>
                                <span>{{ health.scheduler }}</span>
                            </div>
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Время:</span>
                                <span>{{ formatDate(health.timestamp) }}</span>
                            </div>
                        </div>
                        <div v-else class="text-center py-3 text-color-secondary">
                            <i class="pi pi-exclamation-triangle text-2xl mb-2"></i>
                            <p>Не удалось загрузить статус сервиса</p>
                        </div>
                    </template>
                </Card>
            </div>
            <div class="col-12 md:col-6">
                <Card>
                    <template #title>
                        <div class="flex align-items-center">
                            <i class="pi pi-database mr-2"></i>
                            Статус базы данных
                        </div>
                    </template>
                    <template #content>
                        <div v-if="mongoHealthLoading" class="text-center py-3">
                            <ProgressSpinner size="30" />
                        </div>
                        <div v-else-if="mongoHealth" class="space-y-3">
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Статус:</span>
                                <Tag :value="mongoHealth.status" :severity="mongoHealth.status === 'UP' ? 'success' : 'danger'" />
                            </div>
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Сообщение:</span>
                                <span class="text-sm">{{ mongoHealth.message }}</span>
                            </div>
                            <div class="flex justify-content-between align-items-center">
                                <span class="font-medium">Время:</span>
                                <span>{{ formatDate(mongoHealth.timestamp) }}</span>
                            </div>
                            <div v-if="mongoHealth.suggestion" class="mt-3 p-2 bg-orange-50 border-orange-200 rounded">
                                <div class="text-sm text-orange-800">
                                    <i class="pi pi-info-circle mr-1"></i>
                                    {{ mongoHealth.suggestion }}
                                </div>
                            </div>
                        </div>
                        <div v-else class="text-center py-3 text-color-secondary">
                            <i class="pi pi-exclamation-triangle text-2xl mb-2"></i>
                            <p>Не удалось загрузить статус базы данных</p>
                        </div>
                    </template>
                </Card>
            </div>
        </div>

        <!-- Статистика по источникам -->
        <div class="grid">
            <div class="col-12 lg:col-8">
                <Card>
                    <template #title>
                        <div class="flex align-items-center">
                            <i class="pi pi-chart-pie mr-2"></i>
                            Распределение по источникам
                        </div>
                    </template>
                    <template #content>
                        <div v-if="loading" class="text-center py-6">
                            <ProgressSpinner />
                            <p class="mt-3 text-color-secondary">Загрузка статистики...</p>
                        </div>
                        <div v-else-if="!stats.sourceStatistics || Object.keys(stats.sourceStatistics).length === 0" class="text-center py-6">
                            <i class="pi pi-inbox text-4xl text-color-secondary mb-3"></i>
                            <p class="text-color-secondary">Нет данных по источникам</p>
                        </div>
                        <div v-else>
                            <Chart type="pie" :data="chartData" :options="chartOptions" class="w-full" />
                        </div>
                    </template>
                </Card>
            </div>
            <div class="col-12 lg:col-4">
                <Card>
                    <template #title>
                        <div class="flex align-items-center">
                            <i class="pi pi-list mr-2"></i>
                            Детальная статистика
                        </div>
                    </template>
                    <template #content>
                        <div v-if="loading" class="text-center py-3">
                            <ProgressSpinner size="30" />
                        </div>
                        <div v-else-if="!stats.sourceStatistics" class="text-center py-3 text-color-secondary">
                            <p>Нет данных</p>
                        </div>
                        <div v-else class="space-y-3">
                            <div v-for="(count, source) in stats.sourceStatistics" :key="source" class="flex justify-content-between align-items-center p-2 border-round bg-gray-50">
                                <div class="flex align-items-center">
                                    <div class="w-3rem h-3rem border-round flex align-items-center justify-content-center mr-3" :style="{ backgroundColor: getSourceColor(source) }">
                                        <i class="pi pi-align-left text-white"></i>
                                    </div>
                                    <div>
                                        <div class="font-medium text-sm">{{ source }}</div>
                                        <div class="text-xs text-color-secondary">{{ count }} новостей</div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <div class="font-bold text-lg">{{ count }}</div>
                                    <div class="text-xs text-color-secondary">{{ getPercentage(count) }}%</div>
                                </div>
                            </div>
                        </div>
                    </template>
                </Card>
            </div>
        </div>

        <!-- Действия -->
        <div class="flex justify-content-center mt-4">
            <Button label="Перейти к новостям" icon="pi pi-arrow-right" @click="goToNews" severity="info" />
        </div>
    </div>
</template>

<script setup>
import NewsService from '@/service/NewsService';
import Button from 'primevue/button';
import Card from 'primevue/card';
import Chart from 'primevue/chart';
import ProgressSpinner from 'primevue/progressspinner';
import Tag from 'primevue/tag';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// Реактивные данные
const stats = ref({});
const health = ref(null);
const mongoHealth = ref(null);
const loading = ref(false);
const healthLoading = ref(false);
const mongoHealthLoading = ref(false);

// Цвета для источников
const sourceColors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#06B6D4', '#84CC16', '#F97316', '#EC4899', '#6366F1'];

// Вычисляемые свойства
const sourceCount = computed(() => {
    return stats.value.sourceStatistics ? Object.keys(stats.value.sourceStatistics).length : 0;
});

const averagePerSource = computed(() => {
    if (!stats.value.sourceStatistics || sourceCount.value === 0) return 0;
    const total = Object.values(stats.value.sourceStatistics).reduce((sum, count) => sum + count, 0);
    return Math.round(total / sourceCount.value);
});

const chartData = computed(() => {
    if (!stats.value.sourceStatistics) return { labels: [], datasets: [] };

    const sources = Object.keys(stats.value.sourceStatistics);
    const counts = Object.values(stats.value.sourceStatistics);

    return {
        labels: sources,
        datasets: [
            {
                data: counts,
                backgroundColor: sources.map((_, index) => getSourceColor(index)),
                borderWidth: 2,
                borderColor: '#ffffff'
            }
        ]
    };
});

const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
        legend: {
            position: 'bottom',
            labels: {
                padding: 20,
                usePointStyle: true
            }
        },
        tooltip: {
            callbacks: {
                label: function (context) {
                    const label = context.label || '';
                    const value = context.parsed;
                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                    const percentage = ((value / total) * 100).toFixed(1);
                    return `${label}: ${value} новостей (${percentage}%)`;
                }
            }
        }
    }
};

// Методы
const loadData = async () => {
    loading.value = true;
    try {
        await Promise.all([loadStats(), loadHealth(), loadMongoHealth()]);
    } finally {
        loading.value = false;
    }
};

const loadStats = async () => {
    try {
        const response = await NewsService.getStats();
        if (response.success) {
            stats.value = response.data;
        }
    } catch (error) {
        console.error('Ошибка при загрузке статистики:', error);
    }
};

const loadHealth = async () => {
    healthLoading.value = true;
    try {
        const response = await NewsService.getHealth();
        if (response.success) {
            health.value = response.data;
        }
    } catch (error) {
        console.error('Ошибка при загрузке статуса сервиса:', error);
    } finally {
        healthLoading.value = false;
    }
};

const loadMongoHealth = async () => {
    mongoHealthLoading.value = true;
    try {
        const response = await NewsService.getMongoHealth();
        if (response.success) {
            mongoHealth.value = response.data;
        }
    } catch (error) {
        console.error('Ошибка при загрузке статуса MongoDB:', error);
    } finally {
        mongoHealthLoading.value = false;
    }
};

const getSourceColor = (source) => {
    if (typeof source === 'number') {
        return sourceColors[source % sourceColors.length];
    }

    const sources = Object.keys(stats.value.sourceStatistics || {});
    const index = sources.indexOf(source);
    return sourceColors[index % sourceColors.length];
};

const getPercentage = (count) => {
    if (!stats.value.totalItems || stats.value.totalItems === 0) return 0;
    return ((count / stats.value.totalItems) * 100).toFixed(1);
};

const formatDate = (timestamp) => {
    if (!timestamp) return 'Неизвестно';
    return NewsService.formatDate(new Date(timestamp).toISOString());
};

const goToNews = () => {
    router.push('/news');
};

// Жизненный цикл
onMounted(() => {
    loadData();
});
</script>

<style scoped>
.space-y-3 > * + * {
    margin-top: 0.75rem;
}
</style>
