import { Component, inject, computed, input } from '@angular/core';
import { Router } from '@angular/router';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { isaActionChevronLeft } from '@isa/icons';
import { TabService } from './tab';
import { ButtonComponent } from '@isa/ui/buttons';

@Component({
  selector: 'tabs-navigate-back-button',
  imports: [NgIcon, ButtonComponent],
  providers: [provideIcons({ isaActionChevronLeft })],
  template: `
    <button
      uiButton
      color="tertiary"
      size="small"
      class="px-[0.875rem] py-1 min-w-0 bg-white gap-1"
      [class.cursor-not-allowed]="!canNavigateBack()"
      data-what="back-button"
      (click)="back()"
      [disabled]="!canNavigateBack()"
    >
      <ng-icon
        name="isaActionChevronLeft"
        size="1.5rem"
        class="-ml-2"
      ></ng-icon>
      <span>zurück</span>
    </button>
  `,
})
export class NavigateBackButtonComponent {
  #tabService = inject(TabService);
  #router = inject(Router);

  /**
   * Optional URL to navigate to instead of using browser history.
   * Pass a complete URL string (e.g. '/123/reward').
   */
  navigateTo = input<string>();

  canNavigateBack = computed(() => {
    // If navigateTo is set, always allow navigation
    if (this.navigateTo()) {
      return true;
    }

    const tabId = this.#tabService.activatedTabId();
    if (tabId === null) {
      return false;
    }

    const tab = this.#tabService.entityMap()[tabId];
    if (!tab) {
      return false;
    }

    const currentLocation = tab.location;
    return currentLocation.current > 0;
  });

  back() {
    const navigateTo = this.navigateTo();
    if (navigateTo) {
      this.#router.navigateByUrl(navigateTo);
      return;
    }

    // Default behavior: use browser history
    const tabId = this.#tabService.activatedTabId();
    if (tabId === null) {
      return;
    }

    const location = this.#tabService.navigateBack(tabId);

    if (!location) {
      return;
    }

    this.#router.navigateByUrl(location.url);
  }
}
