<template>
    <div class="marketing-strategies-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="goToCreateStrategy" />
                    </div>
                </div>
                <div class="card-content">
                    <DataTable
                        :value="strategies"
                        :loading="loading"
                        paginator
                        :rows="10"
                        :rowsPerPageOptions="[5, 10, 20, 50]"
                        sortMode="multiple"
                        removableSort
                        v-model:multiSortMeta="multiSortMeta"
                        filterDisplay="row"
                        :globalFilterFields="['analysisId', 'status']"
                        v-model:filters="filters"
                        :filters="filters"
                        dataKey="strategyId"
                    >
                        <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="loadStrategies" :loading="loading" />
                            </div>
                        </template>

                        <Column field="analysisId" header="ID анализа" :sortable="true" style="min-width: 200px" :showFilterMenu="false">
                            <template #body="slotProps">
                                <span class="font-mono text-sm">{{ slotProps.data.analysisId }}</span>
                            </template>
                            <template #filter>
                                <span></span>
                            </template>
                        </Column>

                        <Column field="status" header="Статус" :sortable="true" style="min-width: 120px" :showFilterMenu="false">
                            <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()">
                                    <template #option="slotProps">
                                        <Tag :value="slotProps.option.label" :severity="slotProps.option.severity" />
                                    </template>
                                </Dropdown>
                            </template>
                        </Column>

                        <Column field="durationWeeks" header="Длительность" :sortable="true" style="min-width: 120px" :showFilterMenu="false">
                            <template #body="slotProps">
                                <span>{{ slotProps.data.durationWeeks }} {{ pluralize(slotProps.data.durationWeeks, 'неделя', 'недели', 'недель') }}</span>
                            </template>
                            <template #filter>
                                <span></span>
                            </template>
                        </Column>

                        <Column field="priorityPlatforms" header="Платформы" style="min-width: 200px" :showFilterMenu="false">
                            <template #body="slotProps">
                                <div v-if="slotProps.data.priorityPlatforms && slotProps.data.priorityPlatforms.length > 0" class="flex flex-wrap gap-1">
                                    <Tag v-for="platform in slotProps.data.priorityPlatforms" :key="platform" :value="platform" severity="secondary" />
                                </div>
                                <span v-else class="text-surface-400">—</span>
                            </template>
                            <template #filter>
                                <span></span>
                            </template>
                        </Column>

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

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

                        <Column header="Действия" style="min-width: 200px" :showFilterMenu="false" :exportable="false">
                            <template #body="slotProps">
                                <div class="flex gap-2 flex-wrap">
                                    <Button icon="pi pi-eye" severity="info" size="small" v-tooltip.top="'Просмотр деталей'" @click="viewStrategy(slotProps.data.strategyId)" :disabled="slotProps.data.status !== 'completed'" />
                                    <Button icon="pi pi-history" severity="secondary" size="small" v-tooltip.top="'История статусов'" @click="viewHistory(slotProps.data.strategyId)" />
                                </div>
                            </template>
                            <template #filter>
                                <span></span>
                            </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 strategies = ref([]);
const loading = ref(false);
const historyLoading = ref(false);
const statusHistory = ref([]);
const historyDialogVisible = ref(false);
const currentStrategyId = ref(null);

// Filters
const filters = ref({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    status: { value: null, matchMode: FilterMatchMode.EQUALS }
});

// Multi-sort meta (for multiple column sorting)
const multiSortMeta = ref([{ field: 'createdAt', order: -1 }]);

// 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' }
];

// Load strategies
const loadStrategies = async () => {
    loading.value = true;
    try {
        const data = await MarketingService.getMyStrategies();
        // Ensure data is always an array
        strategies.value = Array.isArray(data) ? data : [];
    } catch (error) {
        console.error('Ошибка при загрузке списка стратегий:', error);
        strategies.value = []; // Reset to empty array on error
        toast.add({
            severity: 'error',
            summary: 'Ошибка',
            detail: error.message || 'Не удалось загрузить список стратегий',
            life: 5000
        });
    } finally {
        loading.value = false;
    }
};

// View strategy details
const viewStrategy = (strategyId) => {
    router.push({
        name: 'marketing-promotion',
        query: { strategyId }
    });
};

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

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

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

// 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';
};

// Pluralize
const pluralize = (count, one, few, many) => {
    const mod10 = count % 10;
    const mod100 = count % 100;

    if (mod10 === 1 && mod100 !== 11) return one;
    if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return few;
    return many;
};

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

<style scoped>
.marketing-strategies-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>
