<template>
    <div class="marketing-analyses-list-page bg-surface-50 dark:bg-surface-900 min-h-screen p-6">
        <Toast />
        <div class="max-w-[1400px] mx-auto">
            <div class="card">
                <div class="card-header mb-4">
                    <div class="flex justify-content-between align-items-center">
                        <h2 class="text-2xl font-bold text-surface-900 dark:text-surface-0">Мои анализы</h2>
                        <Button label="Создать новый анализ" icon="pi pi-plus" severity="success" @click="goToCreateAnalysis" />
                    </div>
                </div>
                <div class="card-content">
                    <DataTable
                        :value="analyses || []"
                        :loading="loading"
                        paginator
                        :rows="10"
                        :rowsPerPageOptions="[5, 10, 20, 50]"
                        sortMode="single"
                        removableSort
                        :sortField="'createdAt'"
                        :sortOrder="-1"
                        filterDisplay="menu"
                        :globalFilterFields="['product', 'location', 'region', 'clientType', 'status', 'analysisType', 'businessNiche']"
                        v-model:filters="filters"
                        :filters="filters"
                        dataKey="analysisId"
                    >
                        <template #header>
                            <div class="flex justify-content-between align-items-center flex-wrap gap-2">
                                <span class="p-input-icon-left">
                                    <i class="pi pi-search" />
                                    <InputText v-model="filters.global.value" placeholder="Поиск анализов..." />
                                </span>
                                <Button label="Обновить" icon="pi pi-refresh" severity="secondary" @click="loadAnalyses" :loading="loading" />
                            </div>
                        </template>

                        <Column field="product" header="Продукт" :sortable="true" style="min-width: 200px">
                            <template #body="slotProps">
                                <span class="font-semibold">{{ slotProps.data.product || '—' }}</span>
                            </template>
                        </Column>

                        <Column field="location" header="Локация" :sortable="true" style="min-width: 150px">
                            <template #body="slotProps">
                                <span>{{ slotProps.data.location || '—' }}</span>
                            </template>
                        </Column>

                        <Column field="clientType" header="Тип клиента" :sortable="true" style="min-width: 150px">
                            <template #body="slotProps">
                                <Tag v-if="slotProps.data.clientType && slotProps.data.clientType !== '—'" :value="slotProps.data.clientType" severity="info" />
                                <span v-else class="text-surface-400">—</span>
                            </template>
                        </Column>

                        <Column field="analysisType" header="Тип анализа" :sortable="true" style="min-width: 180px">
                            <template #body="slotProps">
                                <div v-if="slotProps.data.analysisType" class="flex flex-wrap gap-1">
                                    <Tag v-for="(type, index) in Array.isArray(slotProps.data.analysisType) ? slotProps.data.analysisType : [slotProps.data.analysisType]" :key="index" :value="getAnalysisTypeLabel(type)" severity="secondary" />
                                </div>
                                <span v-else class="text-surface-400">—</span>
                            </template>
                        </Column>

                        <Column field="status" header="Статус" :sortable="true" style="min-width: 120px">
                            <template #body="slotProps">
                                <Tag :value="getStatusLabel(slotProps.data.status)" :severity="getStatusSeverity(slotProps.data.status)" />
                            </template>
                            <template #filter="{ filterModel, filterCallback }">
                                <Dropdown v-if="filterModel" v-model="filterModel.value" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="Все статусы" class="p-column-filter" @change="filterCallback && filterCallback()">
                                    <template #option="slotProps">
                                        <Tag :value="slotProps.option.label" :severity="slotProps.option.severity" />
                                    </template>
                                </Dropdown>
                            </template>
                        </Column>

                        <Column field="createdAt" header="Создан" :sortable="true" style="min-width: 180px">
                            <template #body="slotProps">
                                <span>{{ formatDateTime(slotProps.data.createdAt) }}</span>
                            </template>
                        </Column>

                        <Column field="completedAt" header="Завершен" :sortable="true" style="min-width: 180px">
                            <template #body="slotProps">
                                <span v-if="slotProps.data.completedAt">{{ formatDateTime(slotProps.data.completedAt) }}</span>
                                <span v-else class="text-surface-400">—</span>
                            </template>
                        </Column>

                        <Column header="Действия" style="min-width: 250px">
                            <template #body="slotProps">
                                <div class="flex gap-2 flex-wrap">
                                    <Button icon="pi pi-eye" severity="info" size="small" v-tooltip.top="'Просмотр деталей'" @click="viewAnalysis(slotProps.data.analysisId)" :disabled="slotProps.data.status !== 'completed'" />
                                    <Button icon="pi pi-history" severity="secondary" size="small" v-tooltip.top="'История статусов'" @click="viewHistory(slotProps.data.analysisId)" />
                                    <Button icon="pi pi-download" severity="success" size="small" v-tooltip.top="'Скачать PDF'" @click="downloadPdf(slotProps.data.analysisId)" :disabled="slotProps.data.status !== 'completed'" />
                                    <Button icon="pi pi-magic" severity="warning" size="small" v-tooltip.top="'Создать стратегию'" @click="createStrategy(slotProps.data.analysisId)" :disabled="slotProps.data.status !== 'completed'" />
                                </div>
                            </template>
                        </Column>
                    </DataTable>
                </div>
            </div>
        </div>

        <!-- Диалог истории статусов -->
        <Dialog v-model:visible="historyDialogVisible" :header="'История статусов анализа'" :style="{ width: '600px' }" :modal="true">
            <div v-if="historyLoading" class="text-center py-4">
                <ProgressSpinner />
            </div>
            <div v-else-if="statusHistory && statusHistory.length > 0" class="status-history">
                <Timeline :value="statusHistory" align="left" class="w-full">
                    <template #marker="slotProps">
                        <span class="flex w-2rem h-2rem align-items-center justify-content-center text-white border-circle z-1" :class="getStatusColorClass(slotProps.item.status)">
                            <i :class="getStatusIcon(slotProps.item.status)"></i>
                        </span>
                    </template>
                    <template #content="slotProps">
                        <div class="flex flex-column">
                            <div class="flex align-items-center gap-2 mb-2">
                                <Tag :value="getStatusLabel(slotProps.item.status)" :severity="getStatusSeverity(slotProps.item.status)" />
                                <span class="text-sm text-surface-500 dark:text-surface-400">{{ formatDateTime(slotProps.item.timestamp) }}</span>
                            </div>
                            <p class="text-sm text-surface-700 dark:text-surface-300 m-0">{{ slotProps.item.message }}</p>
                        </div>
                    </template>
                </Timeline>
            </div>
            <div v-else class="text-center py-4 text-surface-500">История статусов недоступна</div>
            <template #footer>
                <Button label="Закрыть" icon="pi pi-times" @click="historyDialogVisible = false" severity="secondary" />
            </template>
        </Dialog>
    </div>
</template>

<script setup>
import MarketingService from '@/service/MarketingService';
import { FilterMatchMode } from '@primevue/core/api';
import Button from 'primevue/button';
import Column from 'primevue/column';
import DataTable from 'primevue/datatable';
import Dialog from 'primevue/dialog';
import Dropdown from 'primevue/dropdown';
import InputText from 'primevue/inputtext';
import ProgressSpinner from 'primevue/progressspinner';
import Tag from 'primevue/tag';
import Timeline from 'primevue/timeline';
import Toast from 'primevue/toast';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

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

// Data
const analyses = ref([]);
const loading = ref(false);
const historyLoading = ref(false);
const statusHistory = ref([]);
const historyDialogVisible = ref(false);
const currentAnalysisId = ref(null);

// Filters - initialize with all possible filter fields
const initFilters = () => {
    return {
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
        product: { value: null, matchMode: FilterMatchMode.CONTAINS },
        location: { value: null, matchMode: FilterMatchMode.CONTAINS },
        region: { value: null, matchMode: FilterMatchMode.CONTAINS },
        clientType: { value: null, matchMode: FilterMatchMode.CONTAINS },
        status: { value: null, matchMode: FilterMatchMode.EQUALS },
        analysisType: { value: null, matchMode: FilterMatchMode.CONTAINS },
        businessNiche: { value: null, matchMode: FilterMatchMode.CONTAINS }
    };
};

const filters = ref(initFilters());

// Status options for filter
const statusOptions = [
    { label: 'В очереди', value: 'queued', severity: 'info' },
    { label: 'Обрабатывается', value: 'processing', severity: 'warning' },
    { label: 'Завершен', value: 'completed', severity: 'success' },
    { label: 'Ошибка', value: 'failed', severity: 'danger' }
];

// Normalize analysis data to ensure all required fields exist
const normalizeAnalysis = (analysis) => {
    if (!analysis) {
        return null;
    }

    // Ensure analysisId exists - generate one if missing
    const analysisId = analysis.analysisId || `temp-${Date.now()}-${Math.random()}`;

    // Ensure createdAt exists for sorting - use current date if missing
    const createdAt = analysis.createdAt || new Date().toISOString();

    return {
        ...analysis,
        analysisId,
        product: analysis.product || analysis.businessNiche || '',
        location: analysis.location || analysis.region || '',
        region: analysis.region || analysis.location || '',
        businessNiche: analysis.businessNiche || analysis.product || '',
        clientType: analysis.clientType || '',
        analysisType: analysis.analysisType || null,
        status: analysis.status || 'unknown',
        createdAt: createdAt,
        completedAt: analysis.completedAt || null
    };
};

// Load analyses
const loadAnalyses = async () => {
    loading.value = true;
    try {
        const data = await MarketingService.getMyAnalyses();
        console.log('Raw data from API:', data);

        // Ensure data is an array
        if (!Array.isArray(data)) {
            console.warn('Data is not an array:', data);
            analyses.value = [];
            return;
        }

        // Normalize all analyses to ensure they have all required fields
        // Filter out any null values from normalization
        const normalized = data.map(normalizeAnalysis).filter((analysis) => analysis !== null && analysis !== undefined);

        console.log('Normalized analyses:', normalized);
        analyses.value = normalized;
    } catch (error) {
        console.error('Ошибка при загрузке списка анализов:', error);
        toast.add({
            severity: 'error',
            summary: 'Ошибка',
            detail: error.message || 'Не удалось загрузить список анализов',
            life: 5000
        });
        analyses.value = [];
    } finally {
        loading.value = false;
    }
};

// View analysis details
const viewAnalysis = (analysisId) => {
    router.push({
        name: 'marketing-analysis',
        query: { analysisId }
    });
};

// View history
const viewHistory = async (analysisId) => {
    currentAnalysisId.value = analysisId;
    historyDialogVisible.value = true;
    historyLoading.value = true;
    statusHistory.value = [];

    try {
        const data = await MarketingService.getAnalysisHistory(analysisId);
        statusHistory.value = data.statusHistory || [];
    } catch (error) {
        console.error('Ошибка при загрузке истории:', error);
        toast.add({
            severity: 'error',
            summary: 'Ошибка',
            detail: error.message || 'Не удалось загрузить историю статусов',
            life: 5000
        });
    } finally {
        historyLoading.value = false;
    }
};

// Download PDF
const downloadPdf = async (analysisId) => {
    try {
        await MarketingService.downloadPdfFile(analysisId);
        toast.add({
            severity: 'success',
            summary: 'PDF скачан',
            detail: 'PDF отчет успешно скачан',
            life: 3000
        });
    } catch (error) {
        console.error('Ошибка при скачивании PDF:', error);
        toast.add({
            severity: 'error',
            summary: 'Ошибка',
            detail: error.message || 'Не удалось скачать PDF отчет',
            life: 5000
        });
    }
};

// Create strategy
const createStrategy = (analysisId) => {
    router.push({
        name: 'marketing-promotion',
        query: { analysisId }
    });
};

// Navigate to create analysis
const goToCreateAnalysis = () => {
    router.push({ name: 'marketing-analysis' });
};

// Format date time
const formatDateTime = (dateString) => {
    if (!dateString) return '—';
    const date = new Date(dateString);
    return date.toLocaleString('ru-RU', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
};

// Get status label
const getStatusLabel = (status) => {
    const labels = {
        queued: 'В очереди',
        processing: 'Обрабатывается',
        completed: 'Завершен',
        failed: 'Ошибка'
    };
    return labels[status] || status;
};

// Get status severity
const getStatusSeverity = (status) => {
    const severities = {
        queued: 'info',
        processing: 'warning',
        completed: 'success',
        failed: 'danger'
    };
    return severities[status] || null;
};

// Get status color class for timeline
const getStatusColorClass = (status) => {
    const classes = {
        queued: 'bg-blue-500',
        processing: 'bg-yellow-500',
        completed: 'bg-green-500',
        failed: 'bg-red-500'
    };
    return classes[status] || 'bg-surface-500';
};

// Get status icon
const getStatusIcon = (status) => {
    const icons = {
        queued: 'pi pi-clock',
        processing: 'pi pi-spin pi-spinner',
        completed: 'pi pi-check',
        failed: 'pi pi-times'
    };
    return icons[status] || 'pi pi-circle';
};

// Get analysis type label
const getAnalysisTypeLabel = (type) => {
    const labels = {
        РЫНОК: 'Анализ рынка',
        КОНКУРЕНТЫ: 'Анализ конкурентов',
        ЦА: 'Анализ целевой аудитории',
        КАНАЛЫ: 'Анализ маркетинговых каналов',
        SWOT: 'SWOT-анализ'
    };
    return labels[type] || type;
};

// Load on mount
onMounted(() => {
    loadAnalyses();
});
</script>

<style scoped>
.marketing-analyses-list-page {
    font-family: var(--font-family);
}

.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);
    padding: 1.5rem;
}

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

.card-content {
    padding-top: 0;
}

.status-history {
    max-height: 500px;
    overflow-y: auto;
}
</style>
