import { CommonModule } from '@angular/common';
import { Component, inject, viewChild } from '@angular/core';
import { ActivatedRoute, RouterModule } from '@angular/router';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable, Subject, of } from 'rxjs';
import { mergeMap, switchMap, takeUntil } from 'rxjs/operators';

import { GetOrderStatusAction } from '../../../../shared/action/order-status.action';
import { DownloadInvoiceAction, ViewOrderAction } from '../../../../shared/action/order.action';
import { PayModal } from '../../../../shared/components/widgets/modal/pay-modal/pay-modal';
import { RefundModal } from '../../../../shared/components/widgets/modal/refund-modal/refund-modal';
import { IOrderStatusModel } from '../../../../shared/interface/order-status.interface';
import { IOrder } from '../../../../shared/interface/order.interface';
import { CurrencySymbolPipe } from '../../../../shared/pipe/currency-symbol.pipe';
import { TitleCasePipe } from '../../../../shared/pipe/title-case.pipe';
import { OrderStatusState } from '../../../../shared/state/order-status.state';
import { OrderState } from '../../../../shared/state/order.state';

@Component({
  selector: 'app-order-details',
  imports: [
    CommonModule,
    TranslateModule,
    TitleCasePipe,
    CurrencySymbolPipe,
    RouterModule,
    RefundModal,
    PayModal,
  ],
  templateUrl: './details.html',
  styleUrl: './details.scss',
})
export class OrderDetails {
  private store = inject(Store);
  private route = inject(ActivatedRoute);

  orderStatus$: Observable<IOrderStatusModel> = inject(Store).select(OrderStatusState.orderStatus);

  readonly RefundModal = viewChild<RefundModal>('refundModal');
  readonly PayModal = viewChild<PayModal>('payModal');

  private destroy$ = new Subject<void>();
  public isLogin: boolean;

  public order: IOrder;

  constructor() {
    this.store.dispatch(new GetOrderStatusAction());
  }

  ngOnInit() {
    this.isLogin = !!this.store.selectSnapshot(state => state.auth && state.auth.access_token);
    this.route.params
      .pipe(
        switchMap(params => {
          if (!params['id']) return of();
          return this.store
            .dispatch(new ViewOrderAction(params['id']))
            .pipe(mergeMap(() => this.store.select(OrderState.selectedOrder)));
        }),
        takeUntil(this.destroy$),
      )
      .subscribe(order => {
        this.order = order!;
      });
  }

  download(id: number) {
    this.store.dispatch(new DownloadInvoiceAction({ order_number: id }));
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
