import {
  animate,
  state,
  style,
  transition,
  trigger,
} from '@angular/animations';
import { DecimalPipe } from '@angular/common';
import { Component, Input, OnInit, inject } from '@angular/core';
import { IconComponent } from '@shared/components/icon';
import { BonusCardInfoDTO } from '@generated/swagger/crm-api';
import { injectTabId } from '@isa/core/tabs';
import { NavigationStateService } from '@isa/core/navigation';
import { Router } from '@angular/router';
import { CustomerSearchNavigation } from '@shared/services/navigation';

@Component({
  selector: 'page-customer-kundenkarte',
  templateUrl: 'kundenkarte.component.html',
  styleUrls: ['kundenkarte.component.scss'],
  imports: [IconComponent, DecimalPipe],
  animations: [
    trigger('cardFlip', [
      state(
        'front',
        style({
          transform: 'rotateY(0deg)',
        }),
      ),
      state(
        'back',
        style({
          transform: 'rotateY(0deg)',
        }),
      ),
      state(
        'flip',
        style({
          transform: 'rotateY(90deg)',
        }),
      ),
      transition('front <=> flip', [animate('400ms')]),
      transition('back <=> flip', [animate('400ms')]),
    ]),
  ],
})
export class KundenkarteComponent implements OnInit {
  #tabId = injectTabId();
  #router = inject(Router);
  #navigationState = inject(NavigationStateService);
  #customerNavigationService = inject(CustomerSearchNavigation);

  @Input() cardDetails: BonusCardInfoDTO;
  @Input() isCustomerCard: boolean;
  @Input() customerId: number;

  frontside: boolean;
  state: 'front' | 'flip' | 'back' = 'front';

  ngOnInit() {
    this.frontside = true;
  }

  async navigateToReward() {
    const tabId = this.#tabId();
    const customerId = this.customerId;

    if (!customerId || !tabId) {
      return;
    }

    this.#navigationState.preserveContext(
      {
        returnUrl: `/${tabId}/reward`,
        autoTriggerContinueFn: true,
      },
      'select-customer',
    );

    await this.#router.navigate(
      this.#customerNavigationService.detailsRoute({
        processId: tabId,
        customerId,
      }).path,
    );
  }

  onDeletePartnerCard(): void {}

  flipCard() {
    this.state = 'flip';
  }

  flipAnimationDone(event: any) {
    if (event.fromState === 'front') {
      this.frontside = false;
      this.state = 'back';
    } else if (event.fromState === 'back') {
      this.frontside = true;
      this.state = 'front';
    }
  }
}
