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 '../tenant.service';
import { ToastService } from 'src/app/toast/toast-service';

@Component({
  selector: 'app-add-tenant',

  templateUrl: './add-tenant.component.html',
  styleUrl: './add-tenant.component.scss'
})

export class AddTenantComponent implements OnInit {
  @ViewChild('scrollDataModal', { static: true }) scrollDataModal: TemplateRef<any>;

  @Output() tenantAdded = new EventEmitter<void>();

  addTenantForm: 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.target.value);
    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.addTenantForm.controls; }

  get tenantIdControl(){
    return this.addTenantForm.get('tenantId'); 
  }

  get tenantNameControl(){
    return this.addTenantForm.get('tenantName')
  }

  get phoneControl(){
    return this.addTenantForm.get('phone');
  }

  get primaryEmailControl(){
    return this.addTenantForm.get('primaryEmail');
  }

  onSubmit() {
    this.submitted = true;

    if (this.addTenantForm.invalid) {
      return;
    }
    this.addUser()
  }

  addTenant(data){
    const userid = data.UserID;
    const formData = new URLSearchParams();
    formData.append('tenantUUID', this.addTenantForm.get('tenantId').value);
    formData.append('name', this.addTenantForm.get('tenantName').value);
    formData.append('description', this.addTenantForm.get('description').value);
    formData.append('companyName', this.addTenantForm.get('companyName').value);
    formData.append('address', this.addTenantForm.get('address').value);
    formData.append('primaryEmail', this.addTenantForm.get('primaryEmail').value);
    formData.append('zip', this.addTenantForm.get('zip').value);
    formData.append('phone', this.addTenantForm.get('phone').value);
    formData.append('cityId', this.addTenantForm.get('city').value);
    formData.append('userid', userid);
    this.baseService.postData('tenants/saveTenant', formData).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);

          // task to be done add aothe valu as attributes
          this.tenantAdded.emit();  // Emit event to notify parent component
          // You can also close the modal here if needed
          this.modalService.dismissAll();

          this.addSubscription(data);

          // Set the form as not submitted
          this.submitted = false;

          this.toastService.show('Tenant added successfully!', { classname: 'bg-success text-light', delay: 3000 });
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  addSubscription(data){
    const tenantUUID = data.data.tenantUUID;
    const selectedPlan = this.products.find(product => product.id==Number(this.addTenantForm.get('subscriptions').value))
    console.log(selectedPlan);
    this.baseService.getData(`admin/getAccountDetailByTenant/${tenantUUID}`).subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          const acccountuuid = data.data.accountUUID;
          const formData = 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}`;
          };
  
          formData.append('subscriptionuuid', uuidv4());
          formData.append('planid', this.addTenantForm.get('subscriptions').value );
          formData.append('tenantuuid', tenantUUID);
          formData.append('acccountuuid', acccountuuid);
          formData.append('isfree', 'true');
          formData.append('iscustom', 'false');
          formData.append('iscancelled', 'false');
          formData.append('startson', formatDate(startDate));
          formData.append('ends_at', formatDate(endDate));
          formData.append('currency', 'USD');
          formData.append('createdon', formatDate(startDate));
  
          this.baseService.postData('subscriptions/subscription', formData).subscribe(
            (data: any) => {
              if (data) {
                console.log(data);
                this.addTenantForm.reset();
              }
            },
            (err) => {
              console.log(err);
            }
          );
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  addUser(){
    const formData = new URLSearchParams();
      formData.append('email', this.addTenantForm.get('primaryEmail').value);
      formData.append('username', this.addTenantForm.get('primaryEmail').value);
      formData.append('name', this.addTenantForm.get('tenantName').value);
      formData.append('password', 'Tenant@123');

      this.baseService.postData('user/addUser', formData).subscribe(
        (data: any) => {
          if (data) {
          console.log(data);

          if(this.addTenantForm.get('subscriptions').value==null){
            this.addTenantForm.reset();
          }
          this.addTenant(data)

          }
        },
        (err) => {
          console.log(err);
        }
        );
  }

  openModal() {
    this.modalService.open(this.scrollDataModal, { size: "lg", scrollable: true, windowClass: 'modal-holder', centered: true, backdrop: "static" });

    this.addTenantForm = this.formBuilder.group({
      tenantId: [uuidv4(), Validators.required],
      tenantName: ['', Validators.required],
      companyName: [''],
      primaryEmail: ['',[Validators.email,Validators.required]],
      primaryContact: ['',],
      phone: ['',Validators.required],
      city: [''],
      country: [''],
      zip: [''],
      address: [''],
      description: [''],
      subscriptions:['']
    });

    this.addTenantForm.get('tenantId')?.disable();
  }


}
