<script setup lang="ts">
import { Head, router, usePage } from '@inertiajs/vue3'
import { computed, ref, watch } from 'vue'
import AppLayout from '@/layouts/AppLayout.vue'
import SettingsLayout from '@/layouts/settings/Layout.vue'
import HeadingSmall from '@/components/HeadingSmall.vue'
import type { BreadcrumbItem } from '@/types'

import { Trash, Pencil } from 'lucide-vue-next';
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { toast } from 'vue-sonner'
import 'vue-sonner/style.css'

/* ================= DATA ================= */
const breadcrumbItems: BreadcrumbItem[] = [
    { title: 'Объекты', href: '/settings/objects' },
]

const page = usePage()

const objects = computed(() => page.props.objects as {
    data: { id: number; name: string }[]
    links: { url: string | null; label: string; active: boolean }[]
})

const editingObject = computed(() => page.props.editingObject as { id: number; name: string } | null)

const newObject = ref('')
const editName = ref('')
const editingId = ref<number | null>(null)

/* ================= WATCH ================= */
watch(editingObject, (obj) => {
    if (obj) {
        editingId.value = obj.id
        editName.value = obj.name
    }
}, { immediate: true })

/* ================= ACTIONS ================= */
function addObject() {
    if (!newObject.value.trim()) return

    router.post('/settings/objects', {
        name: newObject.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            newObject.value = ''
            toast.success('Объект успешно добавлен')
        },
    })
}

function startEdit(obj: { id: number; name: string }) {
    router.get(`/settings/objects/${obj.id}/edit`, {}, {
        preserveScroll: true,
        preserveState: true,
    })
}

function updateObject() {
    if (!editingId.value || !editName.value.trim()) return

    router.put(`/settings/objects/${editingId.value}`, {
        name: editName.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            editingId.value = null
            editName.value = ''
            toast.success('Объект успешно обновлён')
        },
    })
}

function cancelEdit() {
    editingId.value = null
    editName.value = ''
    router.get('/settings/objects', {}, {
        preserveScroll: true,
        preserveState: true
    })
}

function deleteObject(id: number) {
    if (confirm('Вы уверены, что хотите удалить этот объект?')) {
        router.delete(`/settings/objects/${id}`, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Объект успешно удалён')
            },
        })
    }
}

function goTo(url: string | null) {
    if (!url) return
    router.visit(url, {
        preserveScroll: true,
        preserveState: true,
    })
}
</script>

<template>
    <AppLayout :breadcrumbs="breadcrumbItems">
        <Head title="Объекты" />

        <SettingsLayout>
            <div class="space-y-6">
                <!-- HEADER -->
                <HeadingSmall title="Объекты" description="Добавление и управление объектами" />

                <!-- ADD -->
                <div class="flex gap-2">
                    <Input
                        v-model="newObject"
                        placeholder="Название объекта"
                        @keydown.enter.prevent="addObject"
                    />
                    <Button @click="addObject">Добавить</Button>
                </div>

                <!-- LIST -->
                <div class="border rounded-xl overflow-hidden">
                    <div
                        v-for="obj in objects.data"
                        :key="obj.id"
                        class="flex items-center justify-between px-4 py-2 hover:bg-muted transition"
                    >
                        <div class="flex-1">
                            <span v-if="editingId !== obj.id" class="text-sm">
                                {{ obj.name }}
                            </span>
                            <Input
                                v-else
                                v-model="editName"
                                class="max-w-xs"
                                @keydown.enter.prevent="updateObject"
                            />
                        </div>

                        <div class="flex items-center gap-3">
                            <Button
                                v-if="editingId !== obj.id"
                                size="sm"
                                variant="outline"
                                @click.stop="startEdit(obj)"
                                class="border-none shadow-none cursor-pointer"
                            >
                                <Pencil class="w-4 h-4" />
                            </Button>

                            <Button
                                v-if="editingId === obj.id"
                                size="sm"
                                @click="updateObject"
                                class="cursor-pointer"
                            >
                                Сохранить
                            </Button>

                            <Button
                                v-if="editingId === obj.id"
                                size="sm"
                                variant="ghost"
                                @click="cancelEdit"
                                class="cursor-pointer"
                            >
                                Отмена
                            </Button>

                            <span
                                class="text-xs text-red-500 cursor-pointer hover:underline"
                                @click.stop="deleteObject(obj.id)"
                            >
                                <Trash class="w-5 h-5" />
                            </span>
                        </div>
                    </div>

                    <div
                        v-if="!objects.data.length"
                        class="text-center text-sm text-muted-foreground py-6"
                    >
                        Нет объектов
                    </div>
                </div>

                <!-- PAGINATION -->
                <div class="flex gap-2 flex-wrap">
                    <Button
                        v-for="(link, i) in objects.links"
                        :key="i"
                        size="sm"
                        variant="outline"
                        :disabled="!link.url"
                        @click="goTo(link.url)"
                        class="cursor-pointer"
                        v-html="link.label"
                    />
                </div>
            </div>
        </SettingsLayout>
    </AppLayout>
</template>
