import { Component, CUSTOM_ELEMENTS_SCHEMA, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { IPaymentMethod, IProduct, IUserData } from '../models/order.interface';
import { OrderService } from '../services/order.service';

@Component({
  selector: 'app-userdatapage',
  imports: [FormsModule],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  templateUrl: './userdatapage.html',
  styleUrl: './userdatapage.scss',
})
export class Userdatapage {

  orderService = inject(OrderService);
  router = inject(Router);
  paymentMethod: 'twint' | 'visa' | 'mastercard' = 'twint';

  get productName() {
    const product: IProduct = JSON.parse(localStorage.getItem('cart') || '{}').product;
    return product?.name;
  }

  get productId() {
    const product: IProduct = JSON.parse(localStorage.getItem('cart') || '{}').product;
    return product?.id;
  }


  public saveData() {
    const contactData: IUserData = {
      firstName: (document.getElementById('firstName') as HTMLInputElement)?.value,
      lastName: (document.getElementById('lastName') as HTMLInputElement)?.value,
      email: (document.getElementById('email') as HTMLInputElement)?.value,
      phone: (document.getElementById('phone') as HTMLInputElement)?.value,
      city: (document.getElementById('city') as HTMLInputElement)?.value,
      address: (document.getElementById('address') as HTMLInputElement)?.value,
      zipCode: (document.getElementById('zipCode') as HTMLInputElement)?.value,
    };

    const cart = JSON.parse(localStorage.getItem('cart') || '{}');

    this.orderService.updateOrder({
      userData: contactData,
      paymentMethod: { type: this.paymentMethod },
      product: cart.product,
      config: cart.config
    });
    console.log(contactData, this.paymentMethod);
  }

  public finishOrder() {
    this.orderService.placeOrder();
    this.router.navigate(['/order-success']);
  }

  public setPaymentMethod(values: any) {
    if (Array.isArray(values) && values.length > 0) {
      this.paymentMethod = values[0] as 'twint' | 'visa' | 'mastercard';
    }
  }
}
