<script setup lang="ts">
import * as LucideIcons from "lucide-vue-next";
import { ChevronRight } from "lucide-vue-next";
import { computed, ref, watch } from "vue";
import { useTranslations } from "../composables/useTranslations";
import { useBuilderPrefix } from "../composables/useBuilderPrefix";
import { useNavigation } from "../composables/useNavigation";
import { Link, usePage } from "@inertiajs/vue3";
import {
  CollapsibleContent,
  CollapsibleRoot,
  CollapsibleTrigger,
} from "reka-ui";
import type { NavigationItem } from "../registry";
import DropdownMenu from "./ui/DropdownMenu.vue";
import DropdownMenuContent from "./ui/DropdownMenuContent.vue";
import DropdownMenuItem from "./ui/DropdownMenuItem.vue";
import DropdownMenuLabel from "./ui/DropdownMenuLabel.vue";
import DropdownMenuSeparator from "./ui/DropdownMenuSeparator.vue";
import DropdownMenuTrigger from "./ui/DropdownMenuTrigger.vue";
import Sidebar from "./ui/sidebar/Sidebar.vue";
import SidebarContent from "./ui/sidebar/SidebarContent.vue";
import SidebarFooter from "./ui/sidebar/SidebarFooter.vue";
import SidebarGroup from "./ui/sidebar/SidebarGroup.vue";
import SidebarHeader from "./ui/sidebar/SidebarHeader.vue";
import SidebarMenu from "./ui/sidebar/SidebarMenu.vue";
import SidebarMenuButton from "./ui/sidebar/SidebarMenuButton.vue";
import SidebarMenuItem from "./ui/sidebar/SidebarMenuItem.vue";
import SidebarMenuSub from "./ui/sidebar/SidebarMenuSub.vue";
import SidebarMenuSubButton from "./ui/sidebar/SidebarMenuSubButton.vue";
import SidebarMenuSubItem from "./ui/sidebar/SidebarMenuSubItem.vue";
import SidebarMenuAction from "./ui/sidebar/SidebarMenuAction.vue";
import SidebarRail from "./ui/sidebar/SidebarRail.vue";
import SidebarUserMenu from "./SidebarUserMenu.vue";
import { useSidebar } from "./ui/sidebar/utils";

const { state, isMobile, setOpenMobile } = useSidebar();
const { t } = useTranslations();
const prefix = useBuilderPrefix();
const { isNavActive: _isNavActive, normalizePath } = useNavigation();

const page = usePage<{
  navigation?: NavigationItem[];
}>();

const navigation = computed(() => page.props.navigation ?? []);

function getIcon(name: string | null | undefined) {
  if (!name) return null;
  return (LucideIcons as Record<string, unknown>)[name] ?? null;
}

function isNavActive(route: string | null | undefined): boolean {
  return _isNavActive(route, page.url);
}

// For top-level items with no children, any sub-path counts as active
// (e.g. /admin/media/folders/my-folder should keep "Media" highlighted).
function isLeafItemActive(route: string | null | undefined): boolean {
  if (!route) return false;
  const routePath = normalizePath(route);
  const current = normalizePath(page.url);
  return current === routePath || current.startsWith(routePath + "/");
}

function isGroupActive(item: NavigationItem): boolean {
  if (isNavActive(item.route)) return true;
  return (item.children ?? []).some(
    (child) =>
      isNavActive(child.route) ||
      (child.children ?? []).some((sub) => isNavActive(sub.route)),
  );
}

// Track which collapsible groups are open (controlled mode)
const openGroups = ref<Record<string, boolean>>({});

// Initialize open groups based on active route and close mobile sidebar on navigation
watch(
  () => page.url,
  (_, oldUrl) => {
    for (const item of navigation.value) {
      if ((item.children ?? []).length > 0 && isGroupActive(item)) {
        openGroups.value[item.key] = true;
      }
    }
    if (oldUrl !== undefined && isMobile.value) {
      setOpenMobile(false);
    }
  },
  { immediate: true },
);
</script>

<template>
  <Sidebar collapsible="icon">
    <SidebarHeader>
      <SidebarMenu>
        <SidebarMenuItem>
          <SidebarMenuButton
            size="lg"
            as-child
            class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
          >
            <Link :href="`/${prefix}/dashboard`">
              <div
                class="flex aspect-square size-8 shrink-0 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground"
              >
                <span class="text-sm font-semibold">B</span>
              </div>
              <div class="grid flex-1 text-left text-sm leading-tight">
                <span class="truncate font-semibold">Builder</span>
                <span class="truncate text-xs">Admin Panel</span>
              </div>
            </Link>
          </SidebarMenuButton>
        </SidebarMenuItem>
      </SidebarMenu>
    </SidebarHeader>

    <SidebarContent>
      <SidebarGroup>
        <SidebarMenu>
          <template v-for="item in navigation" :key="item.key">
            <!-- Items with children -->
            <template v-if="(item.children ?? []).length > 0">
              <!-- Expanded sidebar: collapsible group -->
              <CollapsibleRoot
                v-if="state !== 'collapsed'"
                v-model:open="openGroups[item.key]"
                as-child
                class="group/collapsible"
              >
                <SidebarMenuItem>
                  <!-- Item has a route: label is a link, action toggles collapse -->
                  <template v-if="item.route">
                    <SidebarMenuButton
                      as-child
                      :tooltip="item.label"
                      :is-active="isGroupActive(item)"
                    >
                      <Link :href="item.route">
                        <component
                          :is="getIcon(item.icon)"
                          v-if="getIcon(item.icon)"
                        />
                        <span>{{ item.label }}</span>
                      </Link>
                    </SidebarMenuButton>
                    <CollapsibleTrigger as-child>
                      <SidebarMenuAction>
                        <ChevronRight
                          class="transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90"
                        />
                      </SidebarMenuAction>
                    </CollapsibleTrigger>
                  </template>

                  <!-- Item has no route: entire button toggles collapse -->
                  <template v-else>
                    <CollapsibleTrigger as-child>
                      <SidebarMenuButton
                        :tooltip="item.label"
                        :is-active="isGroupActive(item)"
                      >
                        <component
                          :is="getIcon(item.icon)"
                          v-if="getIcon(item.icon)"
                        />
                        <span>{{ item.label }}</span>
                        <ChevronRight
                          class="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90"
                        />
                      </SidebarMenuButton>
                    </CollapsibleTrigger>
                  </template>

                  <CollapsibleContent>
                    <SidebarMenuSub>
                      <SidebarMenuSubItem
                        v-for="child in item.children"
                        :key="child.key"
                      >
                        <SidebarMenuSubButton
                          as-child
                          :is-active="isNavActive(child.route)"
                        >
                          <Link :href="child.route ?? '#'">
                            <span>{{ child.label }}</span>
                          </Link>
                        </SidebarMenuSubButton>
                      </SidebarMenuSubItem>
                    </SidebarMenuSub>
                  </CollapsibleContent>
                </SidebarMenuItem>
              </CollapsibleRoot>

              <!-- Collapsed sidebar: dropdown -->
              <SidebarMenuItem v-else>
                <DropdownMenu>
                  <DropdownMenuTrigger as-child>
                    <SidebarMenuButton :is-active="isGroupActive(item)">
                      <component
                        :is="getIcon(item.icon)"
                        v-if="getIcon(item.icon)"
                      />
                      <span>{{ item.label }}</span>
                    </SidebarMenuButton>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent
                    side="right"
                    align="start"
                    :side-offset="4"
                    class="min-w-48"
                  >
                    <DropdownMenuLabel class="text-xs text-muted-foreground">{{
                      item.label
                    }}</DropdownMenuLabel>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem
                      v-for="child in item.children"
                      :key="child.key"
                      as-child
                    >
                      <Link
                        :href="child.route ?? '#'"
                        :class="isNavActive(child.route) ? 'font-medium' : ''"
                      >
                        {{ child.label }}
                      </Link>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </SidebarMenuItem>
            </template>

            <!-- Items without children — direct link -->
            <SidebarMenuItem v-else>
              <SidebarMenuButton
                as-child
                :tooltip="item.label"
                :is-active="isLeafItemActive(item.route)"
              >
                <Link :href="item.route ?? '#'">
                  <component
                    :is="getIcon(item.icon)"
                    v-if="getIcon(item.icon)"
                  />
                  <span>{{ item.label }}</span>
                </Link>
              </SidebarMenuButton>
            </SidebarMenuItem>
          </template>
        </SidebarMenu>
      </SidebarGroup>
    </SidebarContent>

    <SidebarFooter>
      <SidebarUserMenu />
    </SidebarFooter>

    <SidebarRail />
  </Sidebar>
</template>
