<template>
    <div class="card">
        <div class="card-header">
            <h5>Управление контентом</h5>
            <Button icon="pi pi-plus" label="Создать контент" @click="showCreateDialog = true" class="p-button-success" />
        </div>
        <div class="card-content">
            <DataTable
                :value="content"
                :loading="loading"
                paginator
                :rows="10"
                :rowsPerPageOptions="[5, 10, 20]"
                sortMode="multiple"
                removableSort
                filterDisplay="row"
                :globalFilterFields="['topic', 'locale', 'status']"
                v-model:filters="filters"
                :filters="filters"
            >
                <template #header>
                    <div class="flex justify-content-between">
                        <span class="p-input-icon-left">
                            <i class="pi pi-search" />
                            <InputText v-model="filters['global'].value" placeholder="Поиск контента..." />
                        </span>
                    </div>
                </template>

                <Column field="topic" header="Тема" :sortable="true">
                    <template #body="slotProps">
                        <span class="font-semibold">{{ slotProps.data.topic }}</span>
                    </template>
                </Column>

                <Column field="locale" header="Локаль" :sortable="true">
                    <template #body="slotProps">
                        <Tag :value="slotProps.data.locale" severity="info" />
                    </template>
                </Column>

                <Column field="campaignId" header="Кампания" :sortable="true">
                    <template #body="slotProps">
                        <span>{{ getCampaignName(slotProps.data.campaignId) }}</span>
                    </template>
                </Column>

                <Column field="postDraft" header="Черновик" :sortable="true">
                    <template #body="slotProps">
                        <span class="text-sm">{{ truncateText(slotProps.data.postDraft, 50) }}</span>
                    </template>
                </Column>

                <Column field="scheduledAt" header="Запланировано" :sortable="true">
                    <template #body="slotProps">
                        <span>{{ formatDate(slotProps.data.scheduledAt) }}</span>
                    </template>
                </Column>

                <Column field="priority" header="Приоритет" :sortable="true">
                    <template #body="slotProps">
                        <Tag :value="slotProps.data.priority" :severity="getPrioritySeverity(slotProps.data.priority)" />
                    </template>
                </Column>

                <Column field="status" header="Статус" :sortable="true">
                    <template #body="slotProps">
                        <Tag :value="getStatusLabel(slotProps.data.status)" :severity="getStatusSeverity(slotProps.data.status)" />
                    </template>
                </Column>

                <Column header="Действия" :exportable="false">
                    <template #body="slotProps">
                        <div class="flex gap-2">
                            <Button icon="pi pi-eye" class="p-button-rounded p-button-text p-button-sm" @click="viewContent(slotProps.data)" v-tooltip.top="'Просмотр'" />
                            <Button icon="pi pi-pencil" class="p-button-rounded p-button-text p-button-sm" @click="editContent(slotProps.data)" v-tooltip.top="'Редактировать'" />
                            <Button v-if="slotProps.data.status === 'PENDING_APPROVAL'" icon="pi pi-check" class="p-button-rounded p-button-text p-button-success p-button-sm" @click="approveContent(slotProps.data)" v-tooltip.top="'Одобрить'" />
                            <Button v-if="slotProps.data.status === 'APPROVED'" icon="pi pi-send" class="p-button-rounded p-button-text p-button-info p-button-sm" @click="publishContent(slotProps.data)" v-tooltip.top="'Опубликовать'" />
                            <Button icon="pi pi-trash" class="p-button-rounded p-button-text p-button-danger p-button-sm" @click="confirmDelete(slotProps.data)" v-tooltip.top="'Удалить'" />
                        </div>
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>

    <!-- Диалог создания/редактирования контента -->
    <Dialog v-model:visible="showCreateDialog" :header="editingContent ? 'Редактировать контент' : 'Создать контент'" :modal="true" :style="{ width: '70vw' }" :closable="false">
        <div class="p-fluid">
            <div class="grid">
                <div class="col-6">
                    <div class="field">
                        <label for="campaignId">Кампания *</label>
                        <Dropdown id="campaignId" v-model="contentForm.campaignId" :options="campaigns" optionLabel="name" optionValue="id" :class="{ 'p-invalid': !contentForm.campaignId }" />
                        <small v-if="!contentForm.campaignId" class="p-error">Кампания обязательна</small>
                    </div>
                </div>
                <div class="col-6">
                    <div class="field">
                        <label for="locale">Локаль *</label>
                        <InputText id="locale" v-model="contentForm.locale" :class="{ 'p-invalid': !contentForm.locale }" />
                        <small v-if="!contentForm.locale" class="p-error">Локаль обязательна</small>
                    </div>
                </div>
            </div>

            <div class="field">
                <label for="topic">Тема *</label>
                <InputText id="topic" v-model="contentForm.topic" :class="{ 'p-invalid': !contentForm.topic }" />
                <small v-if="!contentForm.topic" class="p-error">Тема обязательна</small>
            </div>

            <div class="field">
                <label for="postDraft">Черновик поста</label>
                <Textarea id="postDraft" v-model="contentForm.postDraft" rows="4" />
            </div>

            <div class="field">
                <label for="assetsRefs">Ссылки на ресурсы</label>
                <InputText id="assetsRefs" v-model="contentForm.assetsRefs" />
                <small class="text-600">Разделите ссылки запятыми</small>
            </div>

            <div class="grid">
                <div class="col-6">
                    <div class="field">
                        <label for="scheduledAt">Время публикации</label>
                        <Calendar id="scheduledAt" v-model="contentForm.scheduledAt" dateFormat="yy-mm-dd" showTime hourFormat="24" />
                    </div>
                </div>
                <div class="col-6">
                    <div class="field">
                        <label for="priority">Приоритет</label>
                        <InputNumber id="priority" v-model="contentForm.priority" :min="1" :max="10" />
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <Button label="Отмена" icon="pi pi-times" @click="cancelEdit" class="p-button-text" />
            <Button :label="editingContent ? 'Обновить' : 'Создать'" icon="pi pi-check" @click="saveContent" :loading="saving" />
        </template>
    </Dialog>

    <!-- Диалог просмотра контента -->
    <Dialog v-model:visible="showViewDialog" header="Просмотр контента" :modal="true" :style="{ width: '60vw' }">
        <div v-if="viewingContent" class="content-view">
            <div class="field">
                <label>Тема:</label>
                <p class="font-semibold">{{ viewingContent.topic }}</p>
            </div>
            <div class="field">
                <label>Локаль:</label>
                <p>{{ viewingContent.locale }}</p>
            </div>
            <div class="field">
                <label>Кампания:</label>
                <p>{{ getCampaignName(viewingContent.campaignId) }}</p>
            </div>
            <div class="field">
                <label>Черновик поста:</label>
                <p class="whitespace-pre-wrap">{{ viewingContent.postDraft }}</p>
            </div>
            <div class="field">
                <label>Ссылки на ресурсы:</label>
                <p>{{ viewingContent.assetsRefs }}</p>
            </div>
            <div class="field">
                <label>Время публикации:</label>
                <p>{{ formatDate(viewingContent.scheduledAt) }}</p>
            </div>
            <div class="field">
                <label>Приоритет:</label>
                <p>{{ viewingContent.priority }}</p>
            </div>
            <div class="field">
                <label>Статус:</label>
                <Tag :value="getStatusLabel(viewingContent.status)" :severity="getStatusSeverity(viewingContent.status)" />
            </div>
        </div>
    </Dialog>

    <!-- Диалог подтверждения удаления -->
    <Dialog v-model:visible="showDeleteDialog" header="Подтверждение удаления" :modal="true" :style="{ width: '25vw' }">
        <p>Вы уверены, что хотите удалить контент "{{ contentToDelete?.topic }}"?</p>
        <template #footer>
            <Button label="Отмена" icon="pi pi-times" @click="showDeleteDialog = false" class="p-button-text" />
            <Button label="Удалить" icon="pi pi-trash" @click="deleteContent" class="p-button-danger" :loading="deleting" />
        </template>
    </Dialog>
</template>

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

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

        // Reactive data
        const content = ref([]);
        const campaigns = ref([]);
        const loading = ref(false);
        const saving = ref(false);
        const deleting = ref(false);
        const showCreateDialog = ref(false);
        const showViewDialog = ref(false);
        const showDeleteDialog = ref(false);
        const editingContent = ref(null);
        const viewingContent = ref(null);
        const contentToDelete = ref(null);

        const filters = ref({
            global: { value: null }
        });

        // Content form
        const contentForm = reactive({
            campaignId: '',
            locale: '',
            topic: '',
            postDraft: '',
            assetsRefs: '',
            scheduledAt: null,
            priority: 1
        });

        // Methods
        const loadContent = async () => {
            loading.value = true;
            try {
                content.value = await ContentService.getAllContent();
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось загрузить контент: ' + error.message,
                    life: 3000
                });
            } finally {
                loading.value = false;
            }
        };

        const loadCampaigns = async () => {
            try {
                campaigns.value = await CampaignService.getAllCampaigns();
            } catch (error) {
                console.error('Error loading campaigns:', error);
            }
        };

        const viewContent = (contentItem) => {
            viewingContent.value = contentItem;
            showViewDialog.value = true;
        };

        const editContent = (contentItem) => {
            editingContent.value = contentItem;
            Object.assign(contentForm, {
                campaignId: contentItem.campaignId,
                locale: contentItem.locale,
                topic: contentItem.topic,
                postDraft: contentItem.postDraft,
                assetsRefs: contentItem.assetsRefs,
                scheduledAt: contentItem.scheduledAt ? new Date(contentItem.scheduledAt) : null,
                priority: contentItem.priority
            });
            showCreateDialog.value = true;
        };

        const saveContent = async () => {
            if (!contentForm.campaignId || !contentForm.locale || !contentForm.topic) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка валидации',
                    detail: 'Все обязательные поля должны быть заполнены',
                    life: 3000
                });
                return;
            }

            saving.value = true;
            try {
                const data = {
                    ...contentForm,
                    scheduledAt: contentForm.scheduledAt ? contentForm.scheduledAt.toISOString() : null
                };

                if (editingContent.value) {
                    await ContentService.updateContent(editingContent.value.id, data);
                    toast.add({
                        severity: 'success',
                        summary: 'Успех',
                        detail: 'Контент обновлен',
                        life: 3000
                    });
                } else {
                    await ContentService.createContent(data);
                    toast.add({
                        severity: 'success',
                        summary: 'Успех',
                        detail: 'Контент создан',
                        life: 3000
                    });
                }

                await loadContent();
                cancelEdit();
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось сохранить контент: ' + error.message,
                    life: 3000
                });
            } finally {
                saving.value = false;
            }
        };

        const approveContent = async (contentItem) => {
            try {
                await ContentService.approveContent(contentItem.id);
                toast.add({
                    severity: 'success',
                    summary: 'Успех',
                    detail: 'Контент одобрен',
                    life: 3000
                });
                await loadContent();
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось одобрить контент: ' + error.message,
                    life: 3000
                });
            }
        };

        const publishContent = async (contentItem) => {
            try {
                await PublishingService.publishContent(contentItem.id);
                toast.add({
                    severity: 'success',
                    summary: 'Успех',
                    detail: 'Контент опубликован',
                    life: 3000
                });
                await loadContent();
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось опубликовать контент: ' + error.message,
                    life: 3000
                });
            }
        };

        const cancelEdit = () => {
            editingContent.value = null;
            showCreateDialog.value = false;
            Object.assign(contentForm, {
                campaignId: '',
                locale: '',
                topic: '',
                postDraft: '',
                assetsRefs: '',
                scheduledAt: null,
                priority: 1
            });
        };

        const confirmDelete = (contentItem) => {
            contentToDelete.value = contentItem;
            showDeleteDialog.value = true;
        };

        const deleteContent = async () => {
            deleting.value = true;
            try {
                await ContentService.deleteContent(contentToDelete.value.id);
                toast.add({
                    severity: 'success',
                    summary: 'Успех',
                    detail: 'Контент удален',
                    life: 3000
                });
                await loadContent();
                showDeleteDialog.value = false;
                contentToDelete.value = null;
            } catch (error) {
                toast.add({
                    severity: 'error',
                    summary: 'Ошибка',
                    detail: 'Не удалось удалить контент: ' + error.message,
                    life: 3000
                });
            } finally {
                deleting.value = false;
            }
        };

        const getCampaignName = (campaignId) => {
            const campaign = campaigns.value.find((c) => c.id === campaignId);
            return campaign ? campaign.name : campaignId;
        };

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

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

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

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

        const getPrioritySeverity = (priority) => {
            if (priority >= 8) return 'danger';
            if (priority >= 6) return 'warning';
            if (priority >= 4) return 'info';
            return 'success';
        };

        // Lifecycle
        onMounted(() => {
            loadContent();
            loadCampaigns();
        });

        return {
            content,
            campaigns,
            loading,
            saving,
            deleting,
            showCreateDialog,
            showViewDialog,
            showDeleteDialog,
            editingContent,
            viewingContent,
            contentToDelete,
            filters,
            contentForm,
            loadContent,
            loadCampaigns,
            viewContent,
            editContent,
            saveContent,
            approveContent,
            publishContent,
            cancelEdit,
            confirmDelete,
            deleteContent,
            getCampaignName,
            truncateText,
            formatDate,
            getStatusLabel,
            getStatusSeverity,
            getPrioritySeverity
        };
    }
};
</script>

<style scoped>
.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-content {
    padding: 1.5rem;
}

.field {
    margin-bottom: 1rem;
}

.p-error {
    color: var(--red-500);
    font-size: 0.875rem;
}

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

.content-view .field {
    margin-bottom: 1.5rem;
}

.content-view label {
    font-weight: 600;
    color: var(--text-color-secondary);
    display: block;
    margin-bottom: 0.5rem;
}

.whitespace-pre-wrap {
    white-space: pre-wrap;
}
</style>
