import { Component, inject, input, linkedSignal } from '@angular/core';
import {
  Branch,
  BranchesResource,
  CheckoutMetadataService,
} from '@isa/checkout/data-access';
import { logger } from '@isa/core/logging';
import { DropdownAppearance } from '@isa/ui/input-controls';
import { BranchDropdownComponent } from './branch-dropdown.component';

@Component({
  selector: 'checkout-selected-branch-dropdown',
  template: `
    <checkout-branch-dropdown
      [selected]="selectedBranch()"
      (selectedChange)="selectBranch($event)"
      [appearance]="appearance()"
      data-what="selected-branch-dropdown"
      data-which="checkout-metadata"
    />
  `,
  imports: [BranchDropdownComponent],
  providers: [BranchesResource],
})
export class SelectedBranchDropdownComponent {
  #logger = logger({ component: 'SelectedBranchDropdownComponent' });
  #metadataService = inject(CheckoutMetadataService);

  readonly tabId = input.required<number>();
  readonly appearance = input<DropdownAppearance>(
    DropdownAppearance.AccentOutline,
  );

  readonly selectedBranch = linkedSignal<Branch | null>(() => {
    return this.#metadataService.getSelectedBranch(this.tabId()) ?? null;
  });

  selectBranch(branch: Branch | null) {
    this.#logger.debug('selectBranch', () => ({ branchId: branch?.id }));

    if (branch?.id === this.selectedBranch()?.id) {
      return;
    }

    this.#metadataService.setSelectedBranch(this.tabId(), branch ?? undefined);
  }
}
