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

const page = usePage()

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

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

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

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

/* ================= ACTIONS ================= */
function addPriority() {
    if (!newPriority.value.trim()) return

    router.post('/settings/priorities', {
        name: newPriority.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            newPriority.value = ''
            toast.success('Приоритет успешно добавлен')
        },
    })
}

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

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

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

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

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

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

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

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

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

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