import { IAuthResponse, Maybe, TRoles } from '@/core';
import { ToastService } from '@/core/services/toast.service';
import { Component, EventEmitter, OnDestroy, OnInit, inject, Input, Output, signal } from '@angular/core';
import { Router } from '@angular/router';
import { ButtonDirective } from 'primeng/button';
import images from 'src/assets/images';
import { LoginComponent } from './login/login.component';

type TSteps = 'login' | 'otp' | 'modifyLoginInfo' | 'signup';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  imports: [LoginComponent, ButtonDirective],
})
export class AuthComponent implements OnInit, OnDestroy {
  @Input() redirectUrl!: string;
  @Input() loginApiUrl!: string;
  @Input() role?: TRoles;
  @Input() defaultStep: TSteps = 'login';

  @Output() submit = new EventEmitter<Promise<boolean>>();

  private readonly toastService = inject(ToastService);
  private readonly router = inject(Router);

  readonly logo = images.logo;
  readonly authVector = images.login;

  activeStep = signal<TSteps>(this.defaultStep);

  selectedRole = signal<TRoles | undefined>(this.role);
  accountRole = signal<string>('');

  toSignUp = () => {
    this.activeStep.set('signup');
  };

  onLoggedIn = (data: IAuthResponse) => {
    this.toastService.success({ text: 'شما با موفقیت وارد شدید.' });

    this.selectedRole.set(data.account.type.toUpperCase() as TRoles);
    this.accountRole.set(data.account.role);
    // if (data.mustChangePassword) {
    //   this.activeStep.set('modifyLoginInfo');
    //   return;
    // }

    if (this.submit.observed) {
      return this.submit.emit(Promise.resolve(true));
    }
    this.redirectToDashboard();
  };

  onModifyLoginInfo = () => {
    if (this.submit.observed) {
      return this.submit.emit(Promise.resolve(true));
    }
    this.redirectToDashboard();
  };

  private redirectToDashboard() {
    let redirectUrl = this.redirectUrl;

    if (!redirectUrl) {
      switch (this.selectedRole()) {
        case 'ADMIN':
          redirectUrl = '/super_admin';
          break;
        case 'PROVIDER':
          redirectUrl = '/provider';
          break;
        case 'PARTNER':
          redirectUrl = '/partner';
          break;
        case 'CONSUMER':
          if (this.accountRole() === 'OPERATOR') {
            redirectUrl = '/pos';
          } else {
            redirectUrl = '/consumer';
          }
          break;
      }
    }
    this.router.navigateByUrl(redirectUrl);
  }

  text = signal<string>('waiting for paymentResult...');
  private restorePaymentCallback: Maybe<() => void> = null;
  private readonly injectedPaymentResultHandler = (payload: unknown) => {
    this.handlePaymentResult(payload);
  };

  ngOnInit() {
    this.listenAndroidPaymentResultCallback();
  }

  ngOnDestroy() {
    this.restorePaymentCallback?.();
  }

  private listenAndroidPaymentResultCallback() {
    const w = window as any;
    const previousGlobal = w.onPaymentResult;
    // Android app can call this function directly via evaluateJavascript.
    w.onPaymentResult = this.injectedPaymentResultHandler;

    const bridge = w.AndroidPSP;
    const previousBridge = bridge?.onPaymentResult;
    if (bridge) {
      bridge.onPaymentResult = this.injectedPaymentResultHandler;
    }

    this.restorePaymentCallback = () => {
      w.onPaymentResult = previousGlobal;
      if (bridge) {
        bridge.onPaymentResult = previousBridge;
      }
    };
  }

  private handlePaymentResult(result: unknown) {
    const value = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
    this.text.set(value);
    this.toastService.success({ text: 'Result received from Android.' });
  }

  async pay() {
    //@ts-ignore
    this.toastService.success({ text: window.AndroidPSP.pay(100000) });
    //@ts-ignore
    await window.AndroidPSP?.pay(100000)
      .then((response: any) => {
        // alert('payment')
        // console.log('Payment response:', response);
        this.toastService.success({ text: 'پرداخت با موفقیت انجام شد.' });
      })
      .catch((error: any) => {
        // console.error('Payment error:', error);
        this.toastService.error({ text: 'خطا در انجام پرداخت.' });
      });
    this.toastService.success({ text: 'پرداخت با موفقیت انجام شد.' });
    // //@ts-ignore
    // alert(window.AndroidPSP);
  }

  mockPaymentResult() {
    this.injectedPaymentResultHandler(`test-result-${Date.now()}`);
  }
}
