import { Component, EventEmitter, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AbstractControl, FormBuilder, FormGroup, UntypedFormBuilder, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthenticationService } from 'src/app/core/services/auth.service';
import { UserProfileService } from 'src/app/core/services/user.service';
import { first } from 'rxjs/operators';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { BaseService } from 'src/app/shared/service/base.service';
import { v4 as uuidv4 } from 'uuid';
import { TenantService } from '../customer.service';
import { ToastService } from 'src/app/toast/toast-service';

@Component({
  selector: 'app-add-customer',

  templateUrl: './add-customer.component.html',
  styleUrl: './add-customer.component.scss'
})

export class AddCustomerComponent implements OnInit {
  @ViewChild('scrollDataModal', { static: true }) scrollDataModal: TemplateRef<any>;

  @Output() tenantAdded = new EventEmitter<void>();

  addCustomerForm: FormGroup;
  submitted = false;
  selectedPlan :string=''

  products:any;
  cities: any;
  countries: any;
  filteredCountries: any[] = [];
  countrySearchTerm: string = '';

  constructor(private formBuilder: FormBuilder,
    private modalService: NgbModal,
    public baseService: BaseService,
    public tenantService: TenantService,
    public toastService: ToastService
  ) {

  }
  ngOnInit(): void {
    // this.tenantService.countries$.subscribe(countries => {
    //   this.countries = countries;
    // });

    this.tenantService.countries$.subscribe(data => {
      this.countries = data;
      this.filteredCountries = data;
    });

    this.baseService.getData('subscriptions/getPlans').subscribe(
      (data: any) => {
        if (data && data.data) {
          this.products = data.data;          
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  filterCountries() {
    this.filteredCountries = this.countries.filter(country =>
      country.countryName.toLowerCase().includes(this.countrySearchTerm.toLowerCase())
    );
  }

  onCountryChange(event: any) {
    const selectedCountryid = parseInt(event.id);
    const selectedCountry = this.countries.find(country => country.id === selectedCountryid);
    this.cities = selectedCountry.cities;
    console.log(this.cities);
    this.baseService.getData(`system/cities/${selectedCountry.countryCode}`).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
        }
      },
      (err) => {
        console.log(err);
      }
    );

  }

  get f() { return this.addCustomerForm.controls; }


  get customerNameControl(){
    return this.addCustomerForm.get('CustomerName')
  }

  get phoneControl(){
    return this.addCustomerForm.get('phone');
  }

  get primaryEmailControl(){
    return this.addCustomerForm.get('primaryEmail');
  }

  onSubmit() {
    this.submitted = true;

    if (this.addCustomerForm.invalid) {
      return;
    }
    // this.addUser()
    this.addTenant()

  }

  addTenant(){
    const formData = new URLSearchParams();
    formData.append('customerName', this.addCustomerForm.get('CustomerName').value);
    formData.append('additionalInfo', this.addCustomerForm.get('description').value);
    formData.append('tenantId', 'newTenant');
    formData.append('address', this.addCustomerForm.get('address').value);
    formData.append('email', this.addCustomerForm.get('primaryEmail').value);
    formData.append('zip', this.addCustomerForm.get('zip').value);
    formData.append('phone', this.addCustomerForm.get('phone').value);
    formData.append('cityName', this.addCustomerForm.get('city').value);
    this.baseService.postData('customer/customeradd', formData).subscribe(
      (data: any) => {
        if (data) {

          this.tenantAdded.emit();  // Emit event to notify parent component
          
          this.modalService.dismissAll();

          this.submitted = false;

          this.toastService.show('Customer added successfully!', { classname: 'bg-success text-light', delay: 3000 });
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  openModal() {
    this.modalService.open(this.scrollDataModal, { size: "lg", scrollable: true, windowClass: 'modal-holder', centered: true, backdrop: "static" });

    this.addCustomerForm = this.formBuilder.group({
      CustomerName: ['', Validators.required],
      primaryEmail: ['',[Validators.email,Validators.required]],
      phone: ['',Validators.required],
      city: [''],
      country: [''],
      zip: [''],
      address: [''],
      address2:[''],
      description: [''],
    });
  }


}
