import { computed, type ComputedRef } from "vue";
import { usePage } from "@inertiajs/vue3";
import { useBuilderPrefix } from "./useBuilderPrefix";
import { useNavigation } from "./useNavigation";
import { useTranslations } from "./useTranslations";
import type { NavigationItem } from "../registry";

export type Crumb = { label: string; route: string | null };

export type BreadcrumbsState = {
  breadcrumbs: ComputedRef<Crumb[]>;
  pageTitle: ComputedRef<string | undefined>;
};

export function useBreadcrumbs(): BreadcrumbsState {
  const prefix = useBuilderPrefix();
  const { normalizePath, isNavActive } = useNavigation();
  const { t } = useTranslations();

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

  const settingsNavItems = computed(
    () =>
      (page.props?.navigation ?? []).find((i) => i.key === "settings")
        ?.children ?? [],
  );

  const isSettingsSection = computed(() =>
    settingsNavItems.value.some((i) => isNavActive(i.route, page.url)),
  );

  const isAccountSection = computed(() => {
    const current = normalizePath(page.url);
    return current.startsWith(`/${prefix}/account`);
  });

  const breadcrumbs = computed((): Crumb[] => {
    const nav = page.props?.navigation ?? [];

    if (isSettingsSection.value) {
      const settingsParent = nav.find((i) => i.key === "settings");
      const active = settingsNavItems.value.find((i) =>
        isNavActive(i.route, page.url),
      );
      const parentLabel = settingsParent?.label ?? t("builder.nav.settings");
      const parentRoute =
        settingsNavItems.value.length > 1
          ? (settingsNavItems.value.find((i) => i.key.startsWith("settings."))
              ?.route ??
            settingsNavItems.value[0]?.route ??
            null)
          : null;
      const crumbs: Crumb[] = [{ label: parentLabel, route: parentRoute }];
      if (active) {
        crumbs.push({ label: active.label, route: null });
      }
      return crumbs;
    }

    if (isAccountSection.value) {
      return [{ label: t("builder.account.title"), route: null }];
    }

    for (const item of nav) {
      const children = item.children ?? [];
      if (children.length === 0) {
        if (isNavActive(item.route, page.url)) {
          return [{ label: item.label, route: null }];
        }
      } else {
        if (item.route && isNavActive(item.route, page.url)) {
          return [{ label: item.label, route: null }];
        }
        for (const child of children) {
          if (isNavActive(child.route, page.url)) {
            return [
              {
                label: item.label,
                route:
                  item.route ??
                  (children.length > 1 ? (children[0]?.route ?? null) : null),
              },
              { label: child.label, route: null },
            ];
          }
        }
      }
    }

    return [];
  });

  const pageTitle = computed(() => {
    const crumbs = breadcrumbs.value;
    return crumbs.length > 0 ? crumbs[crumbs.length - 1].label : undefined;
  });

  return { breadcrumbs, pageTitle };
}
