import { CommonModule } from '@angular/common';
import { Component, inject, TemplateRef, viewChild } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';

import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { RePaymentAction } from '../../../../../shared/action/order.action';
import { IOrder } from '../../../../../shared/interface/order.interface';
import { IValues } from '../../../../../shared/interface/setting.interface';
import { SettingState } from '../../../../../shared/state/setting.state';
import { Button } from '../../button/button';

@Component({
  selector: 'app-pay-modal',
  imports: [CommonModule, TranslateModule, ReactiveFormsModule, Button],
  templateUrl: './pay-modal.html',
  styleUrl: './pay-modal.scss',
})
export class PayModal {
  private modalService = inject(NgbModal);
  private store = inject(Store);

  readonly PayModal = viewChild<TemplateRef<string>>('payModal');
  setting$: Observable<IValues> = inject(Store).select(SettingState.setting) as Observable<IValues>;

  public closeResult: string;
  public modalOpen: boolean = false;
  public order: IOrder;
  public paymentType = new FormControl('', [Validators.required]);

  async openModal(order: IOrder) {
    this.order = order;
    this.modalOpen = true;
    this.modalService
      .open(this.PayModal(), {
        ariaLabelledBy: 'profile-Modal',
        centered: true,
        windowClass: 'theme-modal pay-modal',
      })
      .result.then(
        result => {
          `Result ${result}`;
        },
        reason => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        },
      );
  }

  private getDismissReason(reason: ModalDismissReasons): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  submit() {
    this.paymentType.markAllAsTouched();
    if (this.paymentType.valid) {
      const data = {
        order_number: this.order.order_number,
        payment_method: this.paymentType.value!,
      };
      this.store.dispatch(new RePaymentAction(data)).subscribe({
        complete: () => {
          this.modalService.dismissAll();
        },
      });
    }
  }
}
