<script setup lang="ts">
import { SidebarGroup, SidebarGroupLabel, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar';
import { type NavItem } from '@/types';
import { Link, usePage } from '@inertiajs/vue3';
import { onMounted, computed } from 'vue';
import { Resume } from '@/types/resume';
import Button from './ui/button/Button.vue';
import { Plus } from 'lucide-vue-next';
import SidebarListResumeItem from './SidebarListResumeItem.vue';
import { useResumesStore } from '@/stores/resume';

const items = computed<(NavItem & { resume: Resume })[]>(() => {
    return resumeStore.resumes.map((resume: Resume) => ({
        title: resume.name,
        href: route("resumes.edit", resume, false), // false returns only the path
        resume: resume,
    }));
});
const page = usePage();

const resumeStore = useResumesStore();

onMounted(async () => {
    await loadResumes();
});


async function loadResumes() {
    await resumeStore.fetchResumes();
}

function createNewResume() {
    window.location.href = route("resumes.create");
}

function removeResume(deletedResume: Resume) {
    resumeStore.removeResumeById(deletedResume.id);
    if (page.url === route("resumes.edit", deletedResume, false)) {
        // If we are on the deleted resume, redirect to the first resume or to the create page if no resumes left
        if (resumeStore.resumes.length > 0) {
            window.location.href = route("resumes.edit", resumeStore.resumes[0], false);
        } else {
            window.location.href = route("resumes.create");
        }
    }
}
</script>

<template>
    <SidebarGroup class="px-2 py-0">
        <SidebarGroupLabel>Mes CV</SidebarGroupLabel>
        <SidebarMenu>
            <SidebarMenuItem v-for="item in items" :key="item.title">
                <SidebarMenuButton as-child :is-active="item.href === page.url" :tooltip="item.title">
                    <Link :href="item.href">
                        <SidebarListResumeItem :resume="item.resume" @deleted="removeResume" @duplicated="loadResumes" />
                    </Link>
                </SidebarMenuButton>
            </SidebarMenuItem>
            <SidebarMenuItem>
                <SidebarMenuButton as-child class="cursor-pointer text-center" tooltip="Ajouter un composant">
                    <Button variant="outline" size="sm" class="w-full" @click="createNewResume">
                        <Plus />Nouveau CV
                    </Button>
                </SidebarMenuButton>
            </SidebarMenuItem>
        </SidebarMenu>
    </SidebarGroup>
</template>
