<template>
    <div class="smm-dashboard">
        <div class="grid">
            <!-- Заголовок -->
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h4>SMM Система Konturai</h4>
                        <p class="text-600">Управление социальными сетями и контентом</p>
                    </div>
                </div>
            </div>

            <!-- Быстрые действия -->
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5>Быстрые действия</h5>
                    </div>
                    <div class="card-content">
                        <div class="grid">
                            <div class="col-12 md:col-3">
                                <Button label="Создать кампанию" icon="pi pi-plus" class="w-full p-button-success" @click="$router.push('/smm/campaigns')" />
                            </div>
                            <div class="col-12 md:col-3">
                                <Button label="Добавить канал" icon="pi pi-plus" class="w-full p-button-info" @click="$router.push('/smm/channels')" />
                            </div>
                            <div class="col-12 md:col-3">
                                <Button label="Создать контент" icon="pi pi-plus" class="w-full p-button-warning" @click="$router.push('/smm/content')" />
                            </div>
                            <div class="col-12 md:col-3">
                                <Button label="Просмотр аналитики" icon="pi pi-chart-line" class="w-full p-button-secondary" @click="$router.push('/smm/analytics')" />
                            </div>
                        </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-megaphone text-blue-500"></i>
                        </div>
                        <div class="stat-info">
                            <h6>Кампании</h6>
                            <h3>{{ stats.campaigns || 0 }}</h3>
                            <small class="text-600">{{ stats.activeCampaigns || 0 }} активных</small>
                        </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>{{ stats.channels || 0 }}</h3>
                            <small class="text-600">{{ stats.activeChannels || 0 }} активных</small>
                        </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-edit text-orange-500"></i>
                        </div>
                        <div class="stat-info">
                            <h6>Контент</h6>
                            <h3>{{ stats.content || 0 }}</h3>
                            <small class="text-600">{{ stats.pendingApproval || 0 }} ожидает одобрения</small>
                        </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>{{ stats.published || 0 }}</h3>
                            <small class="text-600">{{ stats.publishingRate?.toFixed(1) || 0 }}% успешность</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Последние кампании -->
            <div class="col-12 lg:col-6">
                <div class="card">
                    <div class="card-header">
                        <h6>Последние кампании</h6>
                        <Button label="Все кампании" icon="pi pi-arrow-right" class="p-button-text p-button-sm" @click="$router.push('/smm/campaigns')" />
                    </div>
                    <div class="card-content">
                        <div v-if="loading" class="text-center">
                            <ProgressSpinner />
                        </div>
                        <div v-else-if="recentCampaigns.length === 0" class="text-center text-600">
                            <i class="pi pi-info-circle"></i>
                            <p>Нет кампаний</p>
                        </div>
                        <div v-else class="campaign-list">
                            <div v-for="campaign in recentCampaigns" :key="campaign.id" class="campaign-item">
                                <div class="campaign-info">
                                    <h6>{{ campaign.name }}</h6>
                                    <p class="text-600">{{ campaign.goal }}</p>
                                    <small>{{ formatDate(campaign.startAt) }} - {{ formatDate(campaign.endAt) }}</small>
                                </div>
                                <Tag :value="getStatusLabel(campaign.status)" :severity="getStatusSeverity(campaign.status)" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Последний контент -->
            <div class="col-12 lg:col-6">
                <div class="card">
                    <div class="card-header">
                        <h6>Последний контент</h6>
                        <Button label="Весь контент" icon="pi pi-arrow-right" class="p-button-text p-button-sm" @click="$router.push('/smm/content')" />
                    </div>
                    <div class="card-content">
                        <div v-if="loading" class="text-center">
                            <ProgressSpinner />
                        </div>
                        <div v-else-if="recentContent.length === 0" class="text-center text-600">
                            <i class="pi pi-info-circle"></i>
                            <p>Нет контента</p>
                        </div>
                        <div v-else class="content-list">
                            <div v-for="content in recentContent" :key="content.id" class="content-item">
                                <div class="content-info">
                                    <h6>{{ content.topic }}</h6>
                                    <p class="text-600">{{ truncateText(content.postDraft, 50) }}</p>
                                    <small>{{ formatDate(content.scheduledAt) }}</small>
                                </div>
                                <Tag :value="getContentStatusLabel(content.status)" :severity="getContentStatusSeverity(content.status)" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

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

        // Reactive data
        const stats = ref({});
        const recentCampaigns = ref([]);
        const recentContent = ref([]);
        const loading = ref(false);

        // Methods
        const loadDashboardData = async () => {
            loading.value = true;
            try {
                const [systemStats, publishingStats, campaigns, content] = await Promise.all([AnalyticsService.getSystemStats(), AnalyticsService.getPublishingStats(), CampaignService.getAllCampaigns(), ContentService.getAllContent()]);

                stats.value = {
                    campaigns: systemStats.campaigns?.total || 0,
                    activeCampaigns: systemStats.campaigns?.activeCampaigns || 0,
                    channels: systemStats.channels?.total || 0,
                    activeChannels: systemStats.channels?.activeChannels || 0,
                    content: systemStats.content?.total || 0,
                    pendingApproval: systemStats.content?.pendingApproval || 0,
                    published: publishingStats.totalPublished || 0,
                    publishingRate: publishingStats.publishingRate || 0
                };

                // Получаем последние 5 кампаний
                recentCampaigns.value = campaigns.sort((a, b) => new Date(b.startAt) - new Date(a.startAt)).slice(0, 5);

                // Получаем последние 5 контентов
                recentContent.value = content.sort((a, b) => new Date(b.scheduledAt || b.createdAt) - new Date(a.scheduledAt || a.createdAt)).slice(0, 5);
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось загрузить данные: ' + error.message,
                    life: 3000
                });
            } finally {
                loading.value = false;
            }
        };

        const formatDate = (dateString) => {
            if (!dateString) return '-';
            return new Date(dateString).toLocaleDateString('ru-RU', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        };

        const truncateText = (text, length) => {
            if (!text) return '';
            return text.length > length ? text.substring(0, length) + '...' : text;
        };

        const getStatusLabel = (status) => {
            const labels = {
                [CampaignStatus.PLANNED]: 'Запланирована',
                [CampaignStatus.ACTIVE]: 'Активна',
                [CampaignStatus.COMPLETED]: 'Завершена'
            };
            return labels[status] || status;
        };

        const getStatusSeverity = (status) => {
            const severities = {
                [CampaignStatus.PLANNED]: 'info',
                [CampaignStatus.ACTIVE]: 'success',
                [CampaignStatus.COMPLETED]: 'secondary'
            };
            return severities[status] || 'info';
        };

        const getContentStatusLabel = (status) => {
            const labels = {
                [ContentStatus.DRAFT]: 'Черновик',
                [ContentStatus.PENDING_APPROVAL]: 'Ожидает',
                [ContentStatus.APPROVED]: 'Одобрен',
                [ContentStatus.PUBLISHED]: 'Опубликован',
                [ContentStatus.FAILED]: 'Ошибка'
            };
            return labels[status] || status;
        };

        const getContentStatusSeverity = (status) => {
            const severities = {
                [ContentStatus.DRAFT]: 'info',
                [ContentStatus.PENDING_APPROVAL]: 'warning',
                [ContentStatus.APPROVED]: 'success',
                [ContentStatus.PUBLISHED]: 'success',
                [ContentStatus.FAILED]: 'danger'
            };
            return severities[status] || 'info';
        };

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

        return {
            stats,
            recentCampaigns,
            recentContent,
            loading,
            formatDate,
            truncateText,
            getStatusLabel,
            getStatusSeverity,
            getContentStatusLabel,
            getContentStatusSeverity
        };
    }
};
</script>

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

.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);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

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

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

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

.card-content {
    padding: 1.5rem;
}

.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 0 0.25rem 0;
    font-size: 2rem;
    font-weight: 700;
    color: var(--text-color);
}

.campaign-list,
.content-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.campaign-item,
.content-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    border: 1px solid var(--surface-border);
    border-radius: 8px;
    background: var(--surface-50);
}

.campaign-info,
.content-info {
    flex: 1;
}

.campaign-info h6,
.content-info h6 {
    margin: 0 0 0.5rem 0;
    font-size: 1rem;
    font-weight: 600;
    color: var(--text-color);
}

.campaign-info p,
.content-info p {
    margin: 0 0 0.25rem 0;
    font-size: 0.875rem;
    color: var(--text-color-secondary);
}

.campaign-info small,
.content-info small {
    font-size: 0.75rem;
    color: var(--text-color-secondary);
}

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

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

.w-full {
    width: 100%;
}
</style>
