<template>
    <AppLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <h2 class="text-xl font-bold">Целевые базы данных</h2>
                <Link :href="route('databases.target.create')">
                    <Button icon="pi pi-plus" label="Добавить БД" />
                </Link>
            </div>
        </template>

        <Message v-if="$page.props.flash?.success" severity="success" :life="3000" class="mb-4">
            {{ $page.props.flash.success }}
        </Message>

        <Card>
            <template #content>
                <DataTable :value="databases" stripedRows>
                    <Column field="name" header="Название" sortable></Column>
                    <Column field="host" header="Хост" sortable></Column>
                    <Column field="port" header="Порт" sortable></Column>
                    <Column field="database" header="База данных" sortable></Column>
                    <Column field="driver" header="Драйвер" sortable></Column>
                    <Column field="migration_schedules_count" header="Расписаний" sortable></Column>
                    <Column field="is_active" header="Статус">
                        <template #body="slotProps">
                            <Tag :value="slotProps.data.is_active ? 'Активна' : 'Неактивна'" 
                                 :severity="slotProps.data.is_active ? 'success' : 'danger'" />
                        </template>
                    </Column>
                    <Column header="Действия">
                        <template #body="slotProps">
                            <div class="flex gap-2">
                                <Button icon="pi pi-play" severity="info" size="small" 
                                        @click="testConnection(slotProps.data)" 
                                        title="Проверить подключение" />
                                <Link :href="route('databases.target.edit', slotProps.data.id)">
                                    <Button icon="pi pi-pencil" severity="secondary" size="small" 
                                            title="Редактировать" />
                                </Link>
                                <Button icon="pi pi-trash" severity="danger" size="small" 
                                        @click="confirmDelete(slotProps.data)" 
                                        title="Удалить" />
                            </div>
                        </template>
                    </Column>
                </DataTable>
            </template>
        </Card>

        <Dialog v-model:visible="testingConnection" modal header="Проверка подключения" :style="{ width: '300px' }">
            <div class="flex items-center gap-3">
                <ProgressSpinner style="width: 30px; height: 30px" />
                <span>Проверка подключения к базе данных...</span>
            </div>
        </Dialog>

        <Dialog v-model:visible="deletingDialog" modal header="Подтверждение удаления" :style="{ width: '400px' }">
            <p>Вы уверены, что хотите удалить базу данных "<strong>{{ databaseToDelete?.name }}</strong>"?</p>
            <template #footer>
                <Button label="Отмена" icon="pi pi-times" @click="deletingDialog = false" severity="secondary" />
                <Button label="Удалить" icon="pi pi-trash" @click="deleteDatabase" severity="danger" />
            </template>
        </Dialog>
    </AppLayout>
</template>

<script setup>
import { ref } from 'vue';
import { Link, router } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Tag from 'primevue/tag';
import Message from 'primevue/message';
import Card from 'primevue/card';
import Dialog from 'primevue/dialog';
import ProgressSpinner from 'primevue/progressspinner';

const props = defineProps({
    databases: Array,
});

const testingConnection = ref(false);
const deletingDialog = ref(false);
const databaseToDelete = ref(null);

const testConnection = async (database) => {
    testingConnection.value = true;
    try {
        const response = await fetch(route('databases.target.test', database.id));
        const result = await response.json();
        
        testingConnection.value = false;
        
        if (result.success) {
            alert(`Подключение успешно!\nВерсия PostgreSQL: ${result.version}`);
        } else {
            alert(`Ошибка подключения: ${result.message}`);
        }
    } catch (error) {
        testingConnection.value = false;
        alert(`Ошибка: ${error.message}`);
    }
};

const confirmDelete = (database) => {
    databaseToDelete.value = database;
    deletingDialog.value = true;
};

const deleteDatabase = () => {
    router.delete(route('databases.target.destroy', databaseToDelete.value.id));
    deletingDialog.value = false;
    databaseToDelete.value = null;
};
</script>
