<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="channels"
                :loading="loading"
                paginator
                :rows="10"
                :rowsPerPageOptions="[5, 10, 20]"
                sortMode="multiple"
                removableSort
                filterDisplay="row"
                :globalFilterFields="['name', 'type']"
                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="name" header="Название" :sortable="true">
                    <template #body="slotProps">
                        <span class="font-semibold">{{ slotProps.data.name }}</span>
                    </template>
                </Column>

                <Column field="type" header="Тип" :sortable="true">
                    <template #body="slotProps">
                        <Tag :value="getTypeLabel(slotProps.data.type)" :severity="getTypeSeverity(slotProps.data.type)" />
                    </template>
                </Column>

                <Column field="apiKeyRef" header="API Ключ" :sortable="true">
                    <template #body="slotProps">
                        <span class="font-mono text-sm">{{ slotProps.data.apiKeyRef }}</span>
                    </template>
                </Column>

                <Column field="isActive" header="Статус" :sortable="true">
                    <template #body="slotProps">
                        <Tag :value="slotProps.data.isActive ? 'Активен' : 'Неактивен'" :severity="slotProps.data.isActive ? 'success' : 'danger'" />
                    </template>
                </Column>

                <Column header="Действия" :exportable="false">
                    <template #body="slotProps">
                        <div class="flex gap-2">
                            <Button icon="pi pi-pencil" class="p-button-rounded p-button-text p-button-sm" @click="editChannel(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="editingChannel ? 'Редактировать канал' : 'Создать канал'" :modal="true" :style="{ width: '50vw' }" :closable="false">
        <div class="p-fluid">
            <div class="field">
                <label for="name">Название канала *</label>
                <InputText id="name" v-model="channelForm.name" :class="{ 'p-invalid': !channelForm.name }" />
                <small v-if="!channelForm.name" class="p-error">Название обязательно</small>
            </div>

            <div class="field">
                <label for="type">Тип канала *</label>
                <Dropdown id="type" v-model="channelForm.type" :options="typeOptions" optionLabel="label" optionValue="value" :class="{ 'p-invalid': !channelForm.type }" />
                <small v-if="!channelForm.type" class="p-error">Тип канала обязателен</small>
            </div>

            <div class="field">
                <label for="apiKeyRef">API Ключ *</label>
                <InputText id="apiKeyRef" v-model="channelForm.apiKeyRef" :class="{ 'p-invalid': !channelForm.apiKeyRef }" />
                <small v-if="!channelForm.apiKeyRef" class="p-error">API ключ обязателен</small>
                <small class="text-600">Ссылка на API ключ в системе</small>
            </div>

            <div class="field">
                <div class="flex align-items-center">
                    <Checkbox id="isActive" v-model="channelForm.isActive" :binary="true" />
                    <label for="isActive" class="ml-2">Канал активен</label>
                </div>
            </div>
        </div>

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

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

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

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

        // Reactive data
        const channels = ref([]);
        const loading = ref(false);
        const saving = ref(false);
        const deleting = ref(false);
        const showCreateDialog = ref(false);
        const showDeleteDialog = ref(false);
        const editingChannel = ref(null);
        const channelToDelete = ref(null);

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

        // Channel form
        const channelForm = reactive({
            name: '',
            type: '',
            apiKeyRef: '',
            isActive: true
        });

        // Type options
        const typeOptions = [
            { label: 'Telegram', value: ChannelType.TELEGRAM },
            { label: 'VK', value: ChannelType.VK },
            { label: 'Instagram', value: ChannelType.INSTAGRAM }
        ];

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

        const editChannel = (channel) => {
            editingChannel.value = channel;
            Object.assign(channelForm, {
                name: channel.name,
                type: channel.type,
                apiKeyRef: channel.apiKeyRef,
                isActive: channel.isActive
            });
            showCreateDialog.value = true;
        };

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

            saving.value = true;
            try {
                if (editingChannel.value) {
                    await ChannelService.updateChannel(editingChannel.value.id, channelForm);
                    toast.add({
                        severity: 'success',
                        summary: 'Успех',
                        detail: 'Канал обновлен',
                        life: 3000
                    });
                } else {
                    await ChannelService.createChannel(channelForm);
                    toast.add({
                        severity: 'success',
                        summary: 'Успех',
                        detail: 'Канал создан',
                        life: 3000
                    });
                }

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

        const cancelEdit = () => {
            editingChannel.value = null;
            showCreateDialog.value = false;
            Object.assign(channelForm, {
                name: '',
                type: '',
                apiKeyRef: '',
                isActive: true
            });
        };

        const confirmDelete = (channel) => {
            channelToDelete.value = channel;
            showDeleteDialog.value = true;
        };

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

        const getTypeLabel = (type) => {
            const labels = {
                [ChannelType.TELEGRAM]: 'Telegram',
                [ChannelType.VK]: 'VK',
                [ChannelType.INSTAGRAM]: 'Instagram'
            };
            return labels[type] || type;
        };

        const getTypeSeverity = (type) => {
            const severities = {
                [ChannelType.TELEGRAM]: 'info',
                [ChannelType.VK]: 'warning',
                [ChannelType.INSTAGRAM]: 'success'
            };
            return severities[type] || 'info';
        };

        // Lifecycle
        onMounted(() => {
            loadChannels();
        });

        return {
            channels,
            loading,
            saving,
            deleting,
            showCreateDialog,
            showDeleteDialog,
            editingChannel,
            channelToDelete,
            filters,
            channelForm,
            typeOptions,
            loadChannels,
            editChannel,
            saveChannel,
            cancelEdit,
            confirmDelete,
            deleteChannel,
            getTypeLabel,
            getTypeSeverity
        };
    }
};
</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);
}
</style>
