import { Component, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { v4 as uuidv4 } from 'uuid';
import { BaseService } from 'src/app/shared/service/base.service';
import { TenantService } from '../customer.service';
import { ToastService } from 'src/app/toast/toast-service';
import { SupportLoginMethod,UserData } from '../../../account/auth/login/authList.model';
import { AuthDataList } from '../../../account/auth/login/authListData';


@Component({
  selector: 'app-customer-properties',
  templateUrl: './customer-properties.component.html',
  styleUrls: ['./customer-properties.component.scss']
})
export class CustomerPropertiesComponent implements OnInit {
  @ViewChild('scrollDataModal', { static: true }) scrollDataModal: TemplateRef<any>;

  @Input() tenant: any;

  @Output() tenantAdded = new EventEmitter<void>();

  CustomerFrom: FormGroup;
  AdditionalInfoFrom:FormGroup;
  submitted = false;
  countries:any;
  countryid:'';
  cities:any
  citiesbilling:any
  supportLoginMethods: SupportLoginMethod[] = [];

  selectedMethods: string[] = [];

  products:any;
  myproduct:any;

  activeTab=1;

  languages: string[] = ['English', 'Spanish', 'German', 'French', 'Italian']; // Add your languages here

  constructor(private formBuilder: FormBuilder,
              private modalService: NgbModal,
              public baseService: BaseService,
              public tenantService : TenantService,
              public toastService: ToastService
            ) {

    
              var userData: UserData = AuthDataList; // Fetch userData from your service
              this.supportLoginMethods = userData.support_login_methods
              console.log(this.supportLoginMethods);


    this.CustomerFrom = this.formBuilder.group({
      tenantId: [uuidv4(), Validators.required],
      tenantName: ['', Validators.required],
      createdOn:[''],
      CreatedBy:[''],
      description: ['']
    });

    this.AdditionalInfoFrom = this.formBuilder.group({
      primaryEmail:[''],
      primaryPhone:[''],
      Country: [],
      city:[''],
      address1:[''],
      address2:[''],
      zipCode:[''],
    });
  }

  ngOnInit(): void {
    this.tenantService.countries$.subscribe(countries => {
      this.countries = countries;
    });

    this.baseService.getData('subscriptions/getPlans').subscribe(
      (data: any) => {
        if (data && data.data) {
          this.products = data.data;          
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  getCity(cityId: number) {
    for (let country of this.countries) {
      const city = country.cities.find((city: any) => city.id === cityId);
      if (city) {
        this.countryid = country.id;
        this.cities=country.cities
        break;
      }
    }
    // console.log(this.cities);
    // console.log(this.countryid); 
  }
  getCitybilling(countryId: number) {
    const country = this.countries.find(i => i.id === countryId);
    this.citiesbilling=country.cities
    console.log(this.citiesbilling);
    
  }

  get f() { return this.CustomerFrom.controls; }

  mapTenantToForm(tenant: any) {
    if (tenant) {
      this.CustomerFrom.patchValue({
        tenantId: tenant.customerUUId || uuidv4(),
        tenantName: tenant.customerName || '',
        createdOn:tenant.createdOn||'',
        CreatedBy:tenant.createdBy||'',
        description: tenant.additionalInfo || ''
      });

      if (tenant.city) {
        this.getCity(tenant.city);
      }

      this.AdditionalInfoFrom.patchValue({
        primaryEmail:tenant.email||'',
        address1:tenant.address||'',
        address2:tenant.address2||'',
        primaryPhone:tenant.phone||'',
        Country : this.countryid||'',
        city:tenant.city || '',
        zipCode:tenant.zip || '',
      });


      // Disable the controls
      this.CustomerFrom.get('tenantId')?.disable();
      this.CustomerFrom.get('createdOn')?.disable();
      this.CustomerFrom.get('CreatedBy')?.disable();
    }
  }


  onCountryChange(event:any){
    const selectedCountryid = parseInt(event.target.value);
    const selectedCountry = this.countries.find(country => country.id === selectedCountryid);
    this.cities=selectedCountry.cities;
  }

  onSubmit() {
    this.submitted = true;
    
    if (this.CustomerFrom.invalid) {
      return;
    }
    
    // Handle form submission
    console.log('Form Submitted', this.CustomerFrom.value);

    const formData = new URLSearchParams();
    formData.append('customerName', this.CustomerFrom.get('tenantName').value);
    formData.append('address', this.AdditionalInfoFrom.get('address1').value);
    formData.append('addrress2', this.AdditionalInfoFrom.get('address2').value);
    formData.append('cityName', this.AdditionalInfoFrom.get('city').value);
    formData.append('email', this.AdditionalInfoFrom.get('primaryEmail').value);
    formData.append('phone', this.AdditionalInfoFrom.get('primaryPhone').value);
    formData.append('zip', this.AdditionalInfoFrom.get('zipCode').value);
    formData.append('tenantId', 'updatedTenant');
    formData.append('customerId', this.CustomerFrom.get('tenantId').value);
    formData.append('additionalInfo', this.CustomerFrom.get('description').value);



    this.baseService.postData('customer/customeradd', formData).subscribe(
      response => {
        console.log('Request successful', response);
        this.toastService.show('Tenant Updated successfully!', { classname: 'bg-success text-light', delay: 3000 });

      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  openModal() {
    this.modalService.open(this.scrollDataModal, { size: "lg", scrollable: true, windowClass: 'modal-holder', centered: true, backdrop: "static" });
    console.log(this.tenant);
    this.mapTenantToForm(this.tenant);
    
  }

  dismissModal(){
    this.modalService.dismissAll();
    this.tenantAdded.emit();
    this.CustomerFrom.reset();
    this.AdditionalInfoFrom.reset();
  }

  isMethodSelected(methodName: string): boolean {
    return this.selectedMethods.includes(methodName);
  }

  onMethodChange(event: any, methodName: string): void {
    if (event.target.checked) {
      this.selectedMethods.push(methodName);
    } else {
      const index = this.selectedMethods.indexOf(methodName);
      if (index > -1) {
        this.selectedMethods.splice(index, 1);
      }
    }
    this.AdditionalInfoFrom.patchValue({
      loginMethod: JSON.stringify(this.selectedMethods)
    });
  }
}