<script setup>
import MarketingV3Service from '@/service/MarketingV3Service';
import { useConfirm } from 'primevue/useconfirm';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const toast = useToast();
const confirm = useConfirm();

const analyses = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const filterStatus = ref('');
const currentPage = ref(1);
const pageSize = 10;

const STATUS_FILTERS = [
    { label: 'Все', value: '' },
    { label: 'Завершён', value: 'COMPLETED' },
    { label: 'В работе', value: 'PROCESSING' },
    { label: 'В очереди', value: 'QUEUED' },
    { label: 'Ошибка', value: 'FAILED' }
];

// ─── Load ─────────────────────────────────────────────────────────────────────
const load = async () => {
    loading.value = true;
    try {
        const data = await MarketingV3Service.getUserAnalyses();
        analyses.value = Array.isArray(data) ? data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) : [];
    } catch (err) {
        toast.add({ severity: 'error', summary: 'Ошибка', detail: err.message || 'Не удалось загрузить анализы', life: 5000 });
    } finally {
        loading.value = false;
    }
};

// ─── Filtered & paginated ─────────────────────────────────────────────────────
const filtered = computed(() => {
    let list = analyses.value;
    if (filterStatus.value) list = list.filter((a) => a.status === filterStatus.value);
    if (searchQuery.value.trim()) {
        const q = searchQuery.value.trim().toLowerCase();
        list = list.filter((a) => {
            const niche = (a.requestData?.businessNiche || a.businessNiche || '').toLowerCase();
            const city = cityLabel(a).toLowerCase();
            return niche.includes(q) || city.includes(q);
        });
    }
    return list;
});
const paginated = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return filtered.value.slice(start, start + pageSize);
});

const countByStatus = (s) => analyses.value.filter((a) => a.status === s).length;

// ─── Helpers ──────────────────────────────────────────────────────────────────
const cityLabel = (item) => {
    const rd = item.requestData || item;
    if (rd.mainCity) return rd.mainCity;
    if (rd.presenceCities?.length) return rd.presenceCities.join(', ');
    if (rd.promotionCities?.length) return rd.promotionCities.join(', ');

    // Fallback if none of the above are set but it's a V3 analysis
    if (rd.geoScope === 'FULL_COUNTRY') return 'Вся страна';
    if (rd.geoScope === 'ONLINE') return 'Онлайн';

    return 'География не указана';
};

const formatDate = (dt) => (dt ? new Date(dt).toLocaleString('ru-RU', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '—');

const statusLabel = (s) => ({ COMPLETED: 'Завершён', PROCESSING: 'В работе', QUEUED: 'В очереди', FAILED: 'Ошибка' })[s] || s;

const statusIcon = (s) =>
    ({
        COMPLETED: 'pi pi-check-circle text-emerald-500',
        PROCESSING: 'pi pi-spin pi-spinner text-blue-500',
        QUEUED: 'pi pi-clock text-amber-500',
        FAILED: 'pi pi-times-circle text-red-500'
    })[s] || 'pi pi-circle text-surface-400';

const statusBg = (s) =>
    ({
        COMPLETED: 'bg-emerald-50 dark:bg-emerald-900/20',
        PROCESSING: 'bg-blue-50 dark:bg-blue-900/20',
        QUEUED: 'bg-amber-50 dark:bg-amber-900/20',
        FAILED: 'bg-red-50 dark:bg-red-900/20'
    })[s] || 'bg-surface-100 dark:bg-surface-800';

const statusTagClass = (s) =>
    ({
        COMPLETED: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
        PROCESSING: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
        QUEUED: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
        FAILED: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
    })[s] || 'bg-surface-200 text-surface-600 dark:bg-surface-700 dark:text-surface-300';

// ─── Actions ──────────────────────────────────────────────────────────────────
const openAnalysis = (item) => {
    if (item.status === 'COMPLETED') {
        router.push(`/marketing-analysis/v3/${item.id}`);
    } else if (item.status === 'PROCESSING' || item.status === 'QUEUED') {
        router.push(`/marketing-analysis/v3/${item.id}`);
    }
};

const retry = (item) => {
    router.push('/marketing-analysis/v3/new');
};

const confirmDelete = (item) => {
    confirm.require({
        message: `Удалить анализ "${item.requestData?.businessNiche || 'без названия'}"?`,
        header: 'Подтверждение удаления',
        icon: 'pi pi-exclamation-triangle',
        acceptLabel: 'Удалить',
        rejectLabel: 'Отмена',
        acceptClass: 'p-button-danger',
        accept: () => {
            // TODO: добавить DELETE /api/v3/marketing-analysis/{id} когда появится в API
            analyses.value = analyses.value.filter((a) => a.id !== item.id);
            toast.add({ severity: 'success', summary: 'Удалено', detail: 'Анализ удалён', life: 3000 });
        }
    });
};

onMounted(load);
</script>

<template>
    <div class="bg-surface-50 dark:bg-surface-900 min-h-screen p-4 md:p-6">
        <Toast />

        <!-- ─── Header ─────────────────────────────────────────────────────── -->
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-6">
            <div>
                <div class="flex items-center gap-2 mb-1">
                    <span class="text-xs font-bold tracking-widest uppercase text-primary-500">МАРКЕТИНГОВЫЙ АНАЛИЗ v4.0</span>
                </div>
                <h1 class="text-2xl font-bold text-surface-900 dark:text-surface-0">Мои анализы</h1>
                <p class="text-sm text-surface-500 dark:text-surface-400 mt-0.5">Data-Driven + SMM Execution Ready</p>
            </div>
            <Button label="Создать новый анализ" icon="pi pi-plus" @click="$router.push('/marketing-analysis/v3/new')" class="shrink-0" />
        </div>

        <!-- ─── Search + Filter bar ───────────────────────────────────────── -->
        <div class="card mb-4">
            <div class="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
                <span class="p-input-icon-left flex-1 max-w-xs">
                    <i class="pi pi-search" />
                    <InputText v-model="searchQuery" placeholder="Поиск по нише, городу..." class="w-full text-sm" />
                </span>
                <div class="flex items-center gap-2 flex-wrap">
                    <button
                        v-for="f in STATUS_FILTERS"
                        :key="f.value"
                        @click="filterStatus = f.value"
                        :class="[
                            'px-3 py-1.5 rounded-full text-xs font-semibold transition-all',
                            filterStatus === f.value ? 'bg-primary-500 text-white shadow-sm' : 'bg-surface-200 dark:bg-surface-700 text-surface-600 dark:text-surface-300 hover:bg-surface-300 dark:hover:bg-surface-600'
                        ]"
                    >
                        {{ f.label }}
                        <span v-if="f.value" class="ml-1 opacity-75">({{ countByStatus(f.value) }})</span>
                    </button>
                    <Button icon="pi pi-refresh" severity="secondary" text rounded size="small" :loading="loading" @click="load" v-tooltip.top="'Обновить'" />
                </div>
            </div>
        </div>

        <!-- ─── Loading skeleton ──────────────────────────────────────────── -->
        <div v-if="loading" class="space-y-3">
            <div v-for="i in 4" :key="i" class="card animate-pulse">
                <div class="h-4 bg-surface-200 dark:bg-surface-700 rounded w-1/3 mb-3" />
                <div class="h-3 bg-surface-200 dark:bg-surface-700 rounded w-2/3" />
            </div>
        </div>

        <!-- ─── Empty state ───────────────────────────────────────────────── -->
        <div v-else-if="!filtered.length" class="card text-center py-20">
            <div class="inline-flex items-center justify-center w-20 h-20 rounded-2xl bg-primary-50 dark:bg-primary-900/30 mb-5">
                <i class="pi pi-chart-line text-4xl text-primary-500" />
            </div>
            <h2 class="text-xl font-bold text-surface-900 dark:text-surface-0 mb-2">
                {{ filterStatus ? 'Нет анализов с таким статусом' : 'Анализов пока нет' }}
            </h2>
            <p class="text-sm text-surface-500 dark:text-surface-400 max-w-sm mx-auto mb-6">Запустите первый маркетинговый анализ — ИИ соберёт данные по конкурентам и даст конкретные рекомендации.</p>
            <Button label="Создать первый анализ" icon="pi pi-plus" @click="$router.push('/marketing-analysis/v3/new')" />
        </div>

        <!-- ─── Analysis Cards Grid ───────────────────────────────────────── -->
        <div v-else class="space-y-3">
            <TransitionGroup name="list-fade" tag="div" class="space-y-3">
                <div v-for="item in paginated" :key="item.id" class="card cursor-pointer hover:-translate-y-0.5 hover:shadow-md transition-all duration-200 border border-surface-200 dark:border-surface-700" @click="openAnalysis(item)">
                    <div class="flex flex-col sm:flex-row sm:items-center gap-4">
                        <!-- Status badge -->
                        <div class="shrink-0">
                            <div :class="['w-12 h-12 rounded-xl flex items-center justify-center', statusBg(item.status)]">
                                <i :class="['text-xl', statusIcon(item.status)]" />
                            </div>
                        </div>

                        <!-- Main info -->
                        <div class="flex-1 min-w-0">
                            <div class="flex flex-wrap items-center gap-2 mb-1">
                                <h3 class="text-sm font-bold text-surface-900 dark:text-surface-0 truncate">
                                    {{ item.requestData?.businessNiche || item.businessNiche || 'Анализ #' + item.id?.slice(-6) }}
                                </h3>
                                <span :class="['inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold', statusTagClass(item.status)]">
                                    {{ statusLabel(item.status) }}
                                </span>
                            </div>
                            <div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-surface-500 dark:text-surface-400">
                                <span v-if="item.requestData?.productName || item.productName"> <i class="pi pi-tag mr-1" />{{ item.requestData?.productName || item.productName }} </span>
                                <span v-if="cityLabel(item)"> <i class="pi pi-map-marker mr-1" />{{ cityLabel(item) }} </span>
                                <span v-if="item.requestData?.analysisType?.length"> <i class="pi pi-list mr-1" />{{ (item.requestData.analysisType || []).join(', ') }} </span>
                                <span> <i class="pi pi-calendar mr-1" />{{ formatDate(item.createdAt) }} </span>
                                <span v-if="item.completedAt && item.status === 'COMPLETED'"> <i class="pi pi-check-circle mr-1 text-emerald-500" />{{ formatDate(item.completedAt) }} </span>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="flex items-center gap-1 shrink-0" @click.stop>
                            <Button v-if="item.status === 'COMPLETED'" icon="pi pi-eye" v-tooltip.top="'Открыть дашборд'" severity="info" text rounded size="small" @click="openAnalysis(item)" />
                            <Button v-if="item.status === 'COMPLETED'" icon="pi pi-chart-bar" v-tooltip.top="'Предпросмотр (mock)'" severity="secondary" text rounded size="small" @click="$router.push(`/marketing-analysis/v3/${item.id}?preview=1`)" />
                            <Button v-if="item.status === 'FAILED' || item.status === 'COMPLETED'" icon="pi pi-refresh" v-tooltip.top="'Повторить анализ'" severity="secondary" text rounded size="small" @click="retry(item)" />
                            <Button icon="pi pi-trash" v-tooltip.top="'Удалить'" severity="danger" text rounded size="small" @click="confirmDelete(item)" />
                        </div>
                    </div>

                    <!-- Progress bar for PROCESSING -->
                    <div v-if="item.status === 'PROCESSING' || item.status === 'QUEUED'" class="mt-3">
                        <div class="flex justify-between text-xs text-surface-500 dark:text-surface-400 mb-1">
                            <span>{{ item.status === 'QUEUED' ? 'В очереди...' : 'Анализ выполняется...' }}</span>
                            <span>{{ item.status === 'QUEUED' ? '0%' : '~50%' }}</span>
                        </div>
                        <div class="h-1.5 bg-surface-200 dark:bg-surface-700 rounded-full overflow-hidden">
                            <div class="h-1.5 rounded-full bg-gradient-to-r from-primary-400 to-primary-600 animate-pulse" :style="{ width: item.status === 'QUEUED' ? '10%' : '55%' }" />
                        </div>
                    </div>
                </div>
            </TransitionGroup>

            <!-- Pagination -->
            <div v-if="filtered.length > pageSize" class="flex items-center justify-between pt-2">
                <p class="text-xs text-surface-500 dark:text-surface-400">Показано {{ (currentPage - 1) * pageSize + 1 }}–{{ Math.min(currentPage * pageSize, filtered.length) }} из {{ filtered.length }}</p>
                <Paginator :rows="pageSize" :totalRecords="filtered.length" :first="(currentPage - 1) * pageSize" @page="currentPage = $event.page + 1" template="PrevPageLink PageLinks NextPageLink" />
            </div>
        </div>

        <!-- ─── Delete Confirm Dialog ─────────────────────────────────────── -->
        <ConfirmDialog />
    </div>
</template>

<style scoped>
.list-fade-enter-active,
.list-fade-leave-active {
    transition: all 0.25s ease;
}
.list-fade-enter-from,
.list-fade-leave-to {
    opacity: 0;
    transform: translateY(-8px);
}
</style>
