import { ChangeDetectionStrategy, Component, inject, input } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router, RouterLink } from '@angular/router';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideChevronRight } from '@ng-icons/lucide';
import { HlmCollapsibleImports } from '@spartan-ng/helm/collapsible';
import { HlmSidebarImports } from '@spartan-ng/helm/sidebar';
import { filter, map } from 'rxjs';

import type { NavSubItem } from './types';

@Component({
  selector: 'app-nav-sub-items',
  imports: [HlmSidebarImports, HlmCollapsibleImports, NgIcon, RouterLink],
  providers: [provideIcons({ lucideChevronRight })],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @for (subItem of items(); track subItem.title) {
      @if (subItem.items; as children) {
        <hlm-collapsible [expanded]="isExpanded(subItem)">
          <li hlmSidebarMenuSubItem>
            <button
              class="w-full"
              hlmCollapsibleTrigger
              hlmSidebarMenuSubButton
            >
              @if (subItem.icon) {
                <ng-icon
                  class="text-xs"
                  [name]="subItem.icon"
                />
              }
              {{ subItem.title }}
              <ng-icon
                name="lucideChevronRight"
                class="ml-auto text-xs transition-transform group-data-[state=open]:rotate-90"
              />
            </button>
            <hlm-collapsible-content>
              <ul
                class="ml-2 border-l pl-2"
                hlmSidebarMenuSub
              >
                <app-nav-sub-items [items]="children" />
              </ul>
            </hlm-collapsible-content>
          </li>
        </hlm-collapsible>
      } @else {
        <li hlmSidebarMenuSubItem>
          <a
            [routerLink]="subItem.url"
            hlmSidebarMenuSubButton
            closeMobileSidebarOnClick
          >
            @if (subItem.icon) {
              <ng-icon
                class="text-xs"
                [name]="subItem.icon"
              />
            }
            {{ subItem.title }}
          </a>
        </li>
      }
    }
  `,
})
export class NavSubItems {
  // injections
  private readonly router = inject(Router);

  // inputs
  readonly items = input.required<NavSubItem[]>();

  // signals
  private readonly url = toSignal(
    this.router.events.pipe(
      filter((e) => e instanceof NavigationEnd),
      map(() => this.router.url),
    ),
    { initialValue: this.router.url },
  );

  isExpanded(item: NavSubItem): boolean {
    return this.hasActiveChild(item);
  }

  private hasActiveChild(item: NavSubItem): boolean {
    if (this.url().startsWith(item.url)) return true;
    return item.items?.some((child) => this.hasActiveChild(child)) ?? false;
  }
}
