<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/types-systems' },
]

const page = usePage()

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

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

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

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

/* ================= ACTIONS ================= */
function addSystemType() {
    if (!newSystemType.value.trim()) return

    router.post('/settings/types-systems', {
        name: newSystemType.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            newSystemType.value = ''
            toast.success('Тип системы успешно добавлен')
        },
    })
}

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

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

    router.put(`/settings/types-systems/${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/types-systems', {}, {
        preserveScroll: true,
        preserveState: true
    })
}

function deleteSystemType(id: number) {
    if (confirm('Вы уверены, что хотите удалить этот тип системы?')) {
        router.delete(`/settings/types-systems/${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="newSystemType"
                        placeholder="Название типа системы"
                        @keydown.enter.prevent="addSystemType"
                    />
                    <Button @click="addSystemType">Добавить</Button>
                </div>

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

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

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

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

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

                    <div
                        v-if="!systemTypes.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 systemTypes.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>
