<script lang="ts" setup>
import MainLayout from "@/Layouts/MainLayout.vue"
import GlassBox from "@/Components/FlightsGoneBy/GlassBox.vue"
import { Head } from "@inertiajs/vue3"
import { computed, ref, watch } from "vue"
import type { SettingField } from "@/Types/types"
import CategorySettingsForm from "@/Components/CategorySettingsForm.vue"
import FollowerSettings from "@/Pages/Settings/FollowerSettings.vue"

defineOptions({ layout: MainLayout })

const props = defineProps<{
    fields: SettingField[],
    categories: Record<string, string>,
    defaultTab: string
}>()

const tab = ref(props.defaultTab)

function slugify(name: string) {
    return name
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/(^-|-$)/g, '')
}

const groupedFields = computed(() =>
    props.fields.reduce((groups: Record<string, SettingField[]>, field) => {
        const cat = field.category ?? 'General'
        ;(groups[cat] ??= []).push(field)
        return groups
    }, {} as Record<string, SettingField[]>)
)

const categoryTabs = computed(() =>
    Object.entries(groupedFields.value).map(([name, fields]) => ({
        name,
        slug: slugify(name),
        description: props.categories[name] ?? null,
        fields,
    }))
)

watch(tab, (value) => {
    const path = value === props.defaultTab ? '/settings' : `/settings/${value}`
    window.history.replaceState(window.history.state, '', path)
})
</script>

<template>
    <Head title="Settings" />
    <GlassBox wide title="Your Settings">
        <v-row>
            <v-col cols="12" md="3">
                <v-tabs
                    v-model="tab"
                    direction="vertical"
                    color="primary"
                >
                    <v-tab
                        v-for="cat in categoryTabs"
                        :key="cat.slug"
                        :value="cat.slug"
                        class="justify-start"
                    >
                        {{ cat.name }}
                    </v-tab>
                    <v-tab value="followers" class="justify-start">Followers</v-tab>
                </v-tabs>
            </v-col>

            <v-col cols="12" md="9">
                <v-window v-model="tab">
                    <v-window-item v-for="cat in categoryTabs" :key="cat.slug" :value="cat.slug">
                        <CategorySettingsForm :fields="cat.fields" :description="cat.description" />
                    </v-window-item>

                    <v-window-item value="followers">
                        <FollowerSettings />
                    </v-window-item>
                </v-window>
            </v-col>
        </v-row>
    </GlassBox>
</template>
