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

const page = usePage()

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

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

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

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

/* ================= ACTIONS ================= */
function addType() {
    if (!newType.value.trim()) return

    router.post('/settings/types', {
        name: newType.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            newType.value = ''
            toast.success('Тип заявки успешно добавлен')
        },
    })
}

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

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

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

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

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

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

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

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

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

                    <div
                        v-if="!types.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 types.links"
                        :key="i"
                        size="sm"
                        variant="outline"
                        :disabled="!link.url"
                        @click="goTo(link.url)"
                        v-html="link.label"
                    />
                </div>
            </div>
        </SettingsLayout>
    </AppLayout>
</template>
