<script setup lang="ts">
import { LazyLinkModal } from "#components";

definePageMeta({ middleware: "auth" });

const toast = useToast();
const overlay = useOverlay();

const { fetch: fetchSession } = useUserSession();

const signOut = async () => {
  await $fetch("/api/auth/sign-out", { method: "POST" });
  await fetchSession();
  await navigateTo("/auth/sign-in");
};

const { data: links, status, refresh } = useLazyFetch("/api/links", { key: "links", server: false, });

const route = useRoute();
const category = computed(() => route.query.filter === "disabled" ? "disabled" : "all",);

const filteredLinks = computed(() => {
  if (!links.value) return [];
  if (category.value === "disabled") return links.value.filter((l) => l.disabled);
  return links.value;
});

const openModal = async (link: Link | null) => {
  const modal = overlay.create(LazyLinkModal, { destroyOnClose: true });
  const instance = modal.open({ link });
  if (await instance.result) await refresh();
}

const deleteLink = async (link: Link) => {
  try {
    await $fetch(`/api/links/${link.id}`, { method: "DELETE" });
    toast.add({ title: "Link deleted", color: "success" });
    await refresh();
  } catch {
    toast.add({ title: "Failed to delete link", color: "error" });
  }
}

</script>

<template>
  <UDashboardGroup>
    <UDashboardSidebar :toggle="false">
      <template #header>
        <UDashboardNavbar title="pihka.al" :toggle="false" />
      </template>

      <UNavigationMenu
        orientation="vertical"
        highlight
        :items="[
          {
            label: 'All',
            icon: 'i-lucide-link',
            badge: links?.length ?? 0,
            to: '/',
            active: category === 'all',
          },
          {
            label: 'Disabled',
            icon: 'i-lucide-link-2-off',
            badge: links?.filter((l) => l.disabled).length ?? 0,
            to: '/?filter=disabled',
            active: category === 'disabled',
          },
        ]"
        class="px-2"
      />
      <template #footer>
        <UButton variant="ghost" icon="i-lucide-log-out" block @click="signOut">
          Sign out
        </UButton>
      </template>
    </UDashboardSidebar>

    <UDashboardPanel>
      <template #header>
        <UDashboardNavbar :title="category === 'all' ? 'All links' : 'Disabled links'">
          <template #right>
            <UButton icon="i-lucide-plus" @click="openModal(null)">
              New link
            </UButton>
          </template>
        </UDashboardNavbar>
      </template>

      <template #body>
        <LinksTable
          :data="filteredLinks"
          :status="status"
          @edit="openModal"
          @delete="deleteLink"
        />
      </template>
    </UDashboardPanel>
  </UDashboardGroup>
</template>
