import { Component, inject, TemplateRef, viewChild } from '@angular/core';
import { FormControl, FormGroup, 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 { Select2Data, Select2Module } from 'ng-select2-component';

import { SendRefundRequestAction } from '../../../../../shared/action/refund.action';
import { IProduct } from '../../../../../shared/interface/product.interface';
import { CurrencySymbolPipe } from '../../../../pipe/currency-symbol.pipe';
import { Button } from '../../button/button';

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

  readonly RefundModal = viewChild<TemplateRef<string>>('refundModal');

  public closeResult: string;
  public modalOpen: boolean = false;
  public product: IProduct;
  public form: FormGroup;

  public option: Select2Data = [
    {
      label: 'Wallet',
      value: 'wallet',
    },
    {
      label: 'Paypal',
      value: 'paypal',
    },
    {
      label: 'Bank',
      value: 'bank',
    },
  ];

  constructor() {
    this.form = new FormGroup({
      order_id: new FormControl('', [Validators.required]),
      reason: new FormControl('', [Validators.required]),
      payment_type: new FormControl('', [Validators.required]),
      product_id: new FormControl(),
    });
  }

  async openModal(product: IProduct, order_id: number) {
    this.product = product;
    this.form.controls['order_id'].setValue(order_id);
    this.form.get('product_id')?.patchValue(product.id);
    this.modalOpen = true;
    this.modalService
      .open(this.RefundModal(), {
        ariaLabelledBy: 'profile-Modal',
        centered: true,
        windowClass: 'theme-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}`;
    }
  }

  sendRequest() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.store.dispatch(new SendRefundRequestAction(this.form.value)).subscribe({
        complete: () => {
          this.form.reset();
          this.modalService.dismissAll();
        },
      });
    }
  }
}
