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 '../tenant.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-tenant-properties',
  templateUrl: './tenant-properties.component.html',
  styleUrls: ['./tenant-properties.component.scss']
})
export class TenantPropertiesComponent implements OnInit {
  @ViewChild('scrollDataModal', { static: true }) scrollDataModal: TemplateRef<any>;

  @Input() tenant: any;

  @Output() tenantAdded = new EventEmitter<void>();

  TenantProFrom: FormGroup;
  CompanyInfoFrom:FormGroup;
  AdditionalInfoFrom:FormGroup;
  billingInfoFrom:FormGroup;
  InvoiceInfoFrom:FormGroup
  submitted = false;
  countries:any;
  countryid:'';
  cities:any
  citiesbilling:any
  supportLoginMethods: SupportLoginMethod[] = [];

  selectedMethods: string[] = [];

  products:any;
  myproduct:any;

  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.TenantProFrom = this.formBuilder.group({
      tenantId: [uuidv4(), Validators.required],
      tenantName: ['', Validators.required],
      createdOn:[''],
      CreatedBy:[''],
      description: ['']
    });

    this.CompanyInfoFrom = this.formBuilder.group({
      companyName: [''],
      accountId: [''],
      primaryEmail:[''],
      primaryPhone:[''],
      Country: [],
      city:[''],
      address1:[''],
      address2:[''],
      zipCode:[''],
      onboardingDate:[''],
      subscription:[''],
      description:['']
    });

    this.AdditionalInfoFrom = this.formBuilder.group({
      loginMethod: [''],
      language:[''],
      CompanyQuota:[''],
      support:[''],
      accessExpiry:[''],
      maxusers:['']
    });

    this.billingInfoFrom = this.formBuilder.group({
      country:[''],
      city:[''],
      zipCode:[''],
      address1:[''],
      address2:[''],
    });

    this.InvoiceInfoFrom=this.formBuilder.group({
      companyName:[''],
      email:[''],
      note:['']
    })
  }

  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.TenantProFrom.controls; }

  mapTenantToForm(tenant: any) {
    if (tenant) {
      this.TenantProFrom.patchValue({
        tenantId: tenant.tenantUUID || uuidv4(),
        tenantName: tenant.name || '',
        createdOn:tenant.createdOn||'',
        CreatedBy:tenant.createdBy||'',
        description: tenant.description || ''
      });

      if (tenant.account.cityId) {
        this.getCity(tenant.account.cityId);
      }

      let subscribeid;
      this.baseService.getData(`subscriptions/getSubscriptionbyTenantid/${tenant.tenantUUID}`).subscribe(
        (data: any) => {
          console.log('Subscription data:', data.data); // Log the data to understand its structure
          if (data && data.data) {
            const subscription = data.data; // Single subscription object
            const product = this.products.find(p => p.id === subscription.planId);
            if (product) {
              this.myproduct = [product];
              subscribeid = this.myproduct ? this.myproduct[0].id : ''
              this.CompanyInfoFrom.patchValue({
                subscription: this.myproduct ? this.myproduct[0].id : '' || '',
              });
        
              console.log('Form Submitted', this.CompanyInfoFrom.value);
            }
            
          } else {
            console.error('Invalid subscription data:', data);
          }
        },
        (err) => {
          console.log(err);
        }
      );

      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;
      }, {});

      this.selectedMethods = JSON.parse(settingsMap.support_login_methods || '[]');

      
      this.AdditionalInfoFrom.patchValue({
        maxusers: settingsMap.maxUser || '',
        accessExpiry: settingsMap.accessExpiry || '',
        CompanyQuota: settingsMap.companyQuota || '',
        language: settingsMap.language || '',
        support: settingsMap.support || '',
        loginMethod: JSON.stringify(this.selectedMethods)
      });

      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 || '',
      });


      // Disable the controls
      this.TenantProFrom.get('tenantId')?.disable();
      this.TenantProFrom.get('createdOn')?.disable();
      this.TenantProFrom.get('CreatedBy')?.disable();
      this.CompanyInfoFrom.get('accountId')?.disable();
      this.CompanyInfoFrom.get('onboardingDate')?.disable();
    }
  }


  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;

  }

  onSubmit() {
    this.submitted = true;
    
    if (this.TenantProFrom.invalid) {
      return;
    }
    
    // Handle form submission
    console.log('Form Submitted', this.TenantProFrom.value);
    const tenantId = this.TenantProFrom.get('tenantId').value;
    const formData = new URLSearchParams();
      formData.append('name', this.TenantProFrom.get('tenantName').value);
      formData.append('description', this.TenantProFrom.get('description').value);

    this.baseService.putData(`tenants/${tenantId}`, 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);
      }
    );
  }

  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);
        this.toastService.show('Tenant Updated successfully!', { classname: 'bg-success text-light', delay: 3000 });

      },
      error => {
        console.error('Request failed', error);
      }
    );

    if(this.myproduct[0].id!=this.CompanyInfoFrom.get('subscription').value){
      const formData1 = new URLSearchParams();

      const startDate = new Date();
      const endDate = new Date();
      endDate.setMonth(startDate.getMonth() + 1);

          // Utility function to format date as YYYY-MM-DD
      const formatDate = (date: Date): string => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };
    
      formData1.append('subscriptionuuid', uuidv4());
      formData1.append('planid',this.CompanyInfoFrom.get('subscription').value );
      formData1.append('tenantuuid',this.CompanyInfoFrom.get('tenantId').value);
      formData1.append('acccountuuid',this.TenantProFrom.get('accountId').value);
      formData1.append('isfree', 'true');
      formData1.append('iscustom', 'false');
      formData1.append('iscancelled', 'false');
      formData1.append('startson', formatDate(startDate));
      formData1.append('ends_at', formatDate(endDate));
      formData1.append('currency', 'USD');
      formData1.append('createdon', formatDate(startDate));
      
      this.baseService.postData('subscriptions/subscription', formData1).subscribe(
        (data: any) => {
          if (data) {
            console.log(data);
          }
        },
        (err) => {
        }
      );
    }
  }

  onSubmitAdditionalInfoFrom(){
    const accountId = this.CompanyInfoFrom.get('accountId').value;

    const formData = {
        attributes: {
            maxUser:  this.AdditionalInfoFrom.get('maxusers').value,
            accessExpiry: this.AdditionalInfoFrom.get('accessExpiry').value,
            companyQuota: this.AdditionalInfoFrom.get('CompanyQuota').value,
            language:this.AdditionalInfoFrom.get('language').value,
            support:this.AdditionalInfoFrom.get('support').value,
            support_login_methods: this.AdditionalInfoFrom.get('loginMethod').value
          }
    };
    this.baseService.putJSONData(`admin/${accountId}/property`, 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);
      }
    );
  }

  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);
        this.toastService.show('Tenant Updated successfully!', { classname: 'bg-success text-light', delay: 3000 });

      },
      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);
        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.TenantProFrom.reset();
    this.CompanyInfoFrom.reset();
    this.AdditionalInfoFrom.reset();
    this.billingInfoFrom.reset();
    this.InvoiceInfoFrom.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)
    });
  }
}