<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="loadNews" :loading="loading" severity="secondary" />
        </div>

        <!-- Фильтры -->
        <NewsFilters v-model:filters="filters" @filter-change="onFilterChange" :sources="sources" :loading="loading" />

        <!-- Статистика -->
        <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-2xl mr-3"></i>
                        <div>
                            <div class="text-sm text-blue-600">Всего новостей</div>
                            <div class="text-xl font-semibold text-blue-900">{{ totalElements || 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-2xl mr-3"></i>
                        <div>
                            <div class="text-sm text-green-600">На странице</div>
                            <div class="text-xl font-semibold text-green-900">{{ numberOfElements || 0 }}</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-clock text-orange-500 text-2xl mr-3"></i>
                        <div>
                            <div class="text-sm text-orange-600">Последнее обновление</div>
                            <div class="text-sm font-semibold text-orange-900">{{ lastUpdateTime }}</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-filter text-purple-500 text-2xl mr-3"></i>
                        <div>
                            <div class="text-sm text-purple-600">Активные фильтры</div>
                            <div class="text-xl font-semibold text-purple-900">{{ activeFiltersCount }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Список новостей -->
        <div v-if="loading && news.length === 0" class="text-center py-6">
            <ProgressSpinner />
            <p class="mt-3 text-color-secondary">Загрузка новостей...</p>
        </div>

        <div v-else-if="news.length === 0" class="text-center py-6">
            <i class="pi pi-inbox text-6xl text-color-secondary mb-3"></i>
            <h3 class="text-xl font-semibold mb-2">Новости не найдены</h3>
            <p class="text-color-secondary">Попробуйте изменить фильтры или обновить страницу</p>
        </div>

        <div v-else class="grid">
            <div v-for="item in news" :key="item.id" class="col-12">
                <Card class="mb-3 hover:shadow-2 transition-all transition-duration-200">
                    <template #header>
                        <div class="p-3 pb-0">
                            <div class="flex justify-content-between align-items-start mb-2">
                                <Tag :value="item.sourceName" severity="info" class="mr-2" />
                                <div class="flex align-items-center text-sm text-color-secondary">
                                    <i class="pi pi-calendar mr-1"></i>
                                    {{ formatDate(item.publishedAt) }}
                                </div>
                            </div>
                            <h3 class="text-xl font-semibold mb-2 line-height-3">
                                {{ item.title }}
                            </h3>
                        </div>
                    </template>
                    <template #content>
                        <div class="p-3 pt-0">
                            <p class="text-color-secondary line-height-3 mb-3">
                                {{ getPreviewText(item.rawText) }}
                            </p>
                            <div class="flex justify-content-between align-items-center">
                                <div class="flex align-items-center">
                                    <Tag v-if="item.category" :value="item.category" severity="success" class="mr-2" />
                                    <span class="text-sm text-color-secondary">
                                        <i class="pi pi-clock mr-1"></i>
                                        Добавлено: {{ formatDateShort(item.addedAt) }}
                                    </span>
                                </div>
                                <div class="flex gap-2">
                                    <Button icon="pi pi-external-link" label="Читать" size="small" @click="openNewsDetail(item.id)" severity="secondary" />
                                    <Button icon="pi pi-external-link" size="small" @click="openOriginalUrl(item.url)" severity="info" v-tooltip.top="'Открыть оригинал'" />
                                </div>
                            </div>
                        </div>
                    </template>
                </Card>
            </div>
        </div>

        <!-- Пагинация -->
        <div v-if="totalPages > 1" class="flex justify-content-center mt-4">
            <Paginator
                v-model:first="first"
                :rows="filters.size"
                :totalRecords="totalElements"
                :rowsPerPageOptions="[10, 20, 50, 100]"
                @page="onPageChange"
                template="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
            />
        </div>

        <!-- Кнопка "Загрузить еще" для бесконечной прокрутки -->
        <div v-if="!last && news.length > 0" class="text-center mt-4">
            <Button label="Загрузить еще" icon="pi pi-plus" @click="loadMore" :loading="loadingMore" severity="secondary" />
        </div>
    </div>
</template>

<script setup>
import NewsFilters from '@/components/news/NewsFilters.vue';
import NewsService from '@/service/NewsService';
import Button from 'primevue/button';
import Card from 'primevue/card';
import Paginator from 'primevue/paginator';
import ProgressSpinner from 'primevue/progressspinner';
import Tag from 'primevue/tag';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// Реактивные данные
const news = ref([]);
const loading = ref(false);
const loadingMore = ref(false);
const sources = ref([]);
const first = ref(0);

// Данные пагинации
const totalElements = ref(0);
const totalPages = ref(0);
const numberOfElements = ref(0);
const last = ref(false);

// Фильтры
const filters = reactive({
    page: 0,
    size: 20,
    sort: 'publishedAt,desc',
    sourceName: null,
    startDate: null,
    endDate: null
});

// Вычисляемые свойства
const lastUpdateTime = computed(() => {
    if (news.value.length === 0) return 'Неизвестно';
    const latest = news.value.reduce((latest, item) => {
        return new Date(item.addedAt) > new Date(latest.addedAt) ? item : latest;
    }, news.value[0]);
    return NewsService.formatDateShort(latest.addedAt);
});

const activeFiltersCount = computed(() => {
    let count = 0;
    if (filters.sourceName) count++;
    if (filters.startDate) count++;
    if (filters.endDate) count++;
    return count;
});

// Методы
const loadNews = async (reset = true) => {
    try {
        loading.value = true;

        if (reset) {
            first.value = 0;
            filters.page = 0;
            news.value = [];
        }

        const response = await NewsService.getNewsItems(filters);

        if (response.success) {
            const data = response.data;

            if (reset) {
                news.value = data.content;
            } else {
                news.value.push(...data.content);
            }

            totalElements.value = data.totalElements;
            totalPages.value = data.totalPages;
            numberOfElements.value = data.numberOfElements;
            last.value = data.last;
        }
    } catch (error) {
        console.error('Ошибка при загрузке новостей:', error);
        // Здесь можно добавить уведомление об ошибке
    } finally {
        loading.value = false;
        loadingMore.value = false;
    }
};

const loadMore = async () => {
    if (loadingMore.value || last.value) return;

    loadingMore.value = true;
    filters.page += 1;
    await loadNews(false);
};

const onFilterChange = () => {
    loadNews(true);
};

const onPageChange = (event) => {
    first.value = event.first;
    filters.page = event.page;
    filters.size = event.rows;
    loadNews(true);
};

const openNewsDetail = (id) => {
    router.push(`/news/${id}`);
};

const openOriginalUrl = (url) => {
    window.open(url, '_blank');
};

const getPreviewText = (text) => {
    if (!text) return 'Текст недоступен';
    return text.length > 200 ? text.substring(0, 200) + '...' : text;
};

const formatDate = (dateString) => {
    return NewsService.formatDate(dateString);
};

const formatDateShort = (dateString) => {
    return NewsService.formatDateShort(dateString);
};

const loadSources = async () => {
    try {
        sources.value = await NewsService.getSources();
    } catch (error) {
        console.error('Ошибка при загрузке источников:', error);
    }
};

// Жизненный цикл
onMounted(async () => {
    await loadSources();
    await loadNews();
});

// Отслеживание изменений фильтров
watch(
    () => filters.sourceName,
    () => {
        filters.page = 0;
        first.value = 0;
    }
);

watch(
    () => filters.startDate,
    () => {
        filters.page = 0;
        first.value = 0;
    }
);

watch(
    () => filters.endDate,
    () => {
        filters.page = 0;
        first.value = 0;
    }
);
</script>

<style scoped>
.hover\:shadow-2:hover {
    box-shadow:
        0 4px 6px -1px rgba(0, 0, 0, 0.1),
        0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.transition-all {
    transition: all 0.2s ease-in-out;
}
</style>
