import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { TenantService } from '../tenant/tenant.service';
import { BaseService } from 'src/app/shared/service/base.service';
import { StorageService } from 'src/app/shared/service/storage.service';

@Component({
  selector: 'app-company',
  templateUrl: './company.component.html',
  styleUrls: ['./company.component.scss']
})
export class CompanyComponent implements OnInit {
  // bread crumb items
  breadCrumbItems: Array<{}>;

  CompanyInfoFrom: FormGroup;
  billingInfoFrom: FormGroup;
  InvoiceInfoFrom: FormGroup;
  company: any = {};
  billing: any = {};
  submitted = false;
  countries: any
  cities: any
  citiesbilling: any
  countryid: '';

  constructor(private formBuilder: FormBuilder,
    private tenantService: TenantService,
    private baseService: BaseService,
    private storage: StorageService
  ) {

    this.CompanyInfoFrom = this.formBuilder.group({
      companyName: [''],
      accountId: [''],
      primaryEmail: [''],
      primaryPhone: [''],
      Country: [],
      city: [''],
      address1: [''],
      address2: [''],
      zipCode: [''],
      onboardingDate: [''],
    });

    this.billingInfoFrom = this.formBuilder.group({
      country: [''],
      city: [''],
      zipCode: [''],
      address1: [''],
      address2: [''],
    });

    this.InvoiceInfoFrom = this.formBuilder.group({
      companyName: [''],
      email: [''],
      note: ['']
    })

  }

  ngOnInit() {
    this.tenantService.countries$.subscribe(countries => {
      this.countries = countries;
      this.getCompanyinfo()
    });

  }

  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;
      }
    }
  }

  getCitybilling(countryId: number) {
    const country = this.countries.find(i => i.id === countryId);
    this.citiesbilling = country.cities
    console.log(this.citiesbilling);
  }

  getCompanyinfo() {
    const userid = this.storage.getItem('user');
    this.baseService.getData(`tenants/getbyuserid/${userid}`).subscribe(
      (data: any) => {
        this.mapTenantToForm(data.data[0])
      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  mapTenantToForm(tenant: any) {
    if (tenant) {

      if (tenant.account.cityId) {
        this.getCity(tenant.account.cityId);
      }
      
      this.CompanyInfoFrom.patchValue({
        companyName: tenant.account.accountName || '',
        accountId: tenant.account.accountUUID || '',
        primaryEmail: tenant.account.email || '',
        address1: tenant.account.address || '',
        address2: tenant.account.address2 || '',
        primaryPhone: tenant.account.phone || '',
        onboardingDate: tenant.account.onboardingDate || '',
        Country: this.countryid || '',
        city: tenant.account.cityId || '',
        zipCode: tenant.account.zip || '',
      });

      const settings = tenant.account.accoutSettings || [];
      const settingsMap = settings.reduce((map: any, setting: any) => {
        map[setting.settingName] = setting.settingValue;
        return map;
      }, {});

      if (settingsMap.billingcity) {
        this.getCitybilling(parseInt(settingsMap.billingcountry))
      }
      this.billingInfoFrom.patchValue({
        country: settingsMap.billingcountry || '',
        city: settingsMap.billingcity || '',
        zipCode: settingsMap.billingzipCode || '',
        address1: settingsMap.billingaddress1 || '',
        address2: settingsMap.billingaddress2 || ''
      });


      this.InvoiceInfoFrom.patchValue({
        companyName: settingsMap.invoicecompanyName || '',
        email: settingsMap.invoiceemail || '',
        note: settingsMap.invoicenote || '',
      });
    }

    this.CompanyInfoFrom.get('accountId')?.disable();
    this.CompanyInfoFrom.get('onboardingDate')?.disable();
  }


  onSubmit(companyForm: any) {
    this.submitted = true;
    if (companyForm.invalid) {
      return;
    }
    // Save company logic here
    console.log('Company form submitted', this.company);
  }

  onCountryChange(event: any) {
    const selectedCountryid = parseInt(event.target.value);
    const selectedCountry = this.countries.find(country => country.id === selectedCountryid);
    this.cities = selectedCountry.cities;
  }

  onCountryChangebilling(event: any) {
    const selectedCountryid = parseInt(event.target.value);
    const selectedCountry = this.countries.find(country => country.id === selectedCountryid);
    this.citiesbilling = selectedCountry.cities;

  }

  onSubmitCompanyInfoFrom() {
    const accountId = this.CompanyInfoFrom.get('accountId').value;
    const accountName = this.CompanyInfoFrom.get('companyName').value; // Assuming accountName is another form field
    const formData = {
      attributes: {
        accountname: accountName,
        primaryemail: this.CompanyInfoFrom.get('primaryEmail').value,
        address: this.CompanyInfoFrom.get('address1').value,
        address2: this.CompanyInfoFrom.get('address2').value,
        zip: this.CompanyInfoFrom.get('zipCode').value,
        phone: this.CompanyInfoFrom.get('primaryPhone').value,
        city: this.CompanyInfoFrom.get('city').value,
      }
    };
    this.baseService.putJSONData(`admin/${accountId}/attr`, formData).subscribe(
      response => {
        console.log('Request successful', response);

      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  onSubmitbillingInfoFrom() {
    const accountId = this.CompanyInfoFrom.get('accountId').value;
    const formData = {
      attributes: {
        billingcountry: this.billingInfoFrom.get('country').value,
        billingcity: this.billingInfoFrom.get('city').value,
        billingzipCode: this.billingInfoFrom.get('zipCode').value,
        billingaddress1: this.billingInfoFrom.get('address1').value,
        billingaddress2: this.billingInfoFrom.get('address2').value
      }
    };
    this.baseService.putJSONData(`admin/${accountId}/property`, formData).subscribe(
      response => {
        console.log('Request successful', response);
      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

  onSubmitInvoiceInfoFrom() {
    const accountId = this.CompanyInfoFrom.get('accountId').value;
    const formData = {
      attributes: {
        invoicecompanyName: this.InvoiceInfoFrom.get('companyName').value,
        invoiceemail: this.InvoiceInfoFrom.get('email').value,
        invoicenote: this.InvoiceInfoFrom.get('note').value,
      }
    };
    this.baseService.putJSONData(`admin/${accountId}/property`, formData).subscribe(
      response => {
        console.log('Request successful', response);
      },
      error => {
        console.error('Request failed', error);
      }
    );
  }

}
