import { Component, Input, Output, EventEmitter } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';

import { Subscription } from 'rxjs';

@Component({
  standalone: false,
  selector: 'app-edit-payment-method-modal',
  templateUrl: './edit-payment-method-modal.component.html',
  styleUrls: ['./edit-payment-method-modal.component.scss']
})
export class EditPaymentMethodModalComponent {
  @Input() paymentMethod: any;
  @Input() closeEditPaymentModal!: () => void;
  @Input() fetchPaymentMethods!: () => void;
  months = Array.from({ length: 12 }, (_, i) => i + 1);
  years = Array.from({ length: 30 }, (_, i) => new Date().getFullYear() + i);
  resultSubscribe!:Subscription;
  validationErr: string = "";
  form = {
    name: '',
    exp_month: null,
    exp_year: null,
  };

  constructor(private http: HttpClient, private accountInfoService: AccountInfoService) {}

  ngOnInit(): void {
    if (this.paymentMethod) {
      this.form.name = this.paymentMethod.name_on_card || '';
      this.form.exp_month = this.paymentMethod.exp_month;
      this.form.exp_year = this.paymentMethod.exp_year;
    }
  }

  ngOnChanges() {
    if (this.paymentMethod) {
      this.form.name = this.paymentMethod.name_on_card || '';
      this.form.exp_month = this.paymentMethod.exp_month;
      this.form.exp_year = this.paymentMethod.exp_year;
    }
  }

  submit() {
    this.validationErr = "Invalid expiration month/year";
    const currentMonth = new Date().getMonth() + 1; // 1-12
    const currentYear = new Date().getFullYear();
    const expMonth = this?.form?.exp_month;
    const expYear = this?.form?.exp_year;
    if (expYear && expMonth && ((expYear > currentYear) ||(expYear === currentYear && expMonth >= currentMonth))) {
        this.validationErr = "";
        const payload = {
            'paymentMethodId' : this.paymentMethod.stripe_payment_id,
            'updateData' : {
              'billing_details[name]': this.form.name,
              'card[exp_month]': this.form.exp_month,
              'card[exp_year]': this.form.exp_year
            }
        };
        this.resultSubscribe = this.accountInfoService.updatePaymentMethod(payload)
        .subscribe({
          next: () => {
            this.closeEditPaymentModal();
          },
          error: (err: HttpErrorResponse) => {
            this.accountInfoService.errorCallBack(err);
          },
          complete: () => { },
        });
    }
  }

  resetValidateMsg()
  {
     this.validationErr = "";
  }

  ngOnDestroy(){
    this.resultSubscribe?.unsubscribe();
  }
}
