import { Component, ElementRef, OnInit, QueryList, ViewChildren } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import { FormsModule, NgForm } from '@angular/forms';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { CommonModule } from '@angular/common';
import { NgSelectModule } from '@ng-select/ng-select';
import { NgxMatIntlTelInputComponent } from 'ngx-mat-intl-tel-input';
import moment from 'moment-timezone';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';

@Component({
  selector: 'app-customers-edit',
  templateUrl: './customers-edit.component.html',
  styleUrls: ['./customers-edit.component.scss'],
  standalone : true,
  imports : [CommonModule, AdminPageHeaderComponent, TranslatePipes, NgSelectModule, NgxMatIntlTelInputComponent, FormsModule ]
})
export class CustomersEditComponent extends Unsub implements OnInit {
  timezones;
  timezone;
  id: number | any;
  customerData: any;
  customfield: any = {};countries : any;
  customfields: any = [];
  public sendingResponse: { [key: string]: boolean } = {};
  constructor(
    private toastr: ToastrService,
    private router: Router,
    private activeRoute: ActivatedRoute,
    private adminService: AdminService,
    private translate: TranslatePipe,
    loaderService: LoaderService
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);
    this.timezones = moment.tz.names();
    this.activeRoute.paramMap.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.id = params.get('id');
        this.loaderService.showLoader();
        this.adminService
          .editCustomerData(this.id)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              this.customerData = res?.user;
              this.countries = res.countries;
              this.customfields = res?.customfield;
              this.timezone = this.customerData?.timezone;
              if (res?.customfield) {
                
                res.customfield.forEach((element) => {
                  if (
                    (element.fieldtypes == 'radio' ||
                    element.fieldtypes == 'checkbox')
                    ) {
                      let value;
                      if(element.values?.startsWith('[')){
                        value = JSON.parse(element.values);
                      }else{
                        value = element.values;
                      }
                    this.customfield['custom_' + element.id] = {
                      status: element.fieldrequired,
                      val: value,
                    };
                    if (element.fieldrequired == 1) {
                      this.checkStatus = true;
                    }
                  }
                });
              }
              this.loaderService.hideLoader();
            },
            error : ()=> this.loaderService.hideLoader()
          });
      },
    });
  }
  ngOnInit(): void { }
  public timeZoneChanged(timeZone: string): void {
    this.timezone = timeZone;
  }


  editCustomer(ngForm: NgForm, buttonId) {
    
    const cf = this.customfield;
    const newCf = {};
    for (const i in cf) {
      const e = cf[i].val;
      newCf[i] = e;
    }
    const data = { ...ngForm.value, ...newCf };
    data['country'] = this.customerData.country;
    data['timezone'] = this.customerData.timezone;
    if (ngForm.value.voilated == true || ngForm.value.voilated == 'on') {
      data['voilated'] = 'on';
    }
    this.sendingResponse[buttonId] = true;

    this.adminService
      .editCustomer(this.id, data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (response: any) => {
          this.sendingResponse[buttonId] = false;
          if (response?.success) {
            this.toastr.success(this.translate.transform(response.success));
            this.router.navigate(['/admin/customer']);
          }
          if (response?.error) {
            this.toastr.error(this.translate.transform(response.error));
          }
          if (response?.error?.message) {
            this.toastr.error(this.translate.transform(response.error.message));
          }
        },
        error: () => {
           this.sendingResponse[buttonId] = false;
        },
      });
  }

  checkStatus = false;
  checkCount: any[] = [];
  customfieldSection(res, name, type): void {    
    this.checkStatus = true;
    this.checkCount = [];
    if (type == 'radio') {
      this.customfield[name].val = res;
    }
    if (type == 'checkbox') {     
      if (this.customfield[name]?.val?.includes(res)) {
        this.customfield[name].val = this.customfield[name].val.filter((x) => {
          return x != res;
        });
      } else {
          if (this.customfield[name].val) {
            this.customfield[name].val.push(res);
          } else {
            this.customfield[name].val = [res];
          }
      }
    }
    for (const i in this.customfield) {
        if (this.customfield[i]?.val?.length) {
          continue;
        } else {
          this.checkCount.push(this.customfield[i]);
        }
    }
    if (this.checkCount.length) {
      this.checkStatus = true;
    } else {
      this.checkStatus = false;
    }
  }

  @ViewChildren('filterInput') filterInput!: QueryList<ElementRef>;
  dropdownSearch() {
    this.filterInput.changes.subscribe(res => {
      if (this.filterInput?.first) {
        this.filterInput.first.nativeElement.focus()
      }
    })
  }

  addTagFn(name: any) {
    return name;
  }

  checkcheckboxOtions(arr, val){
    if (!arr) return false;

  let values = [];

  try {
    // Try to parse as JSON
    values = JSON.parse(arr);

    // If parsed result is not an array, wrap in array
    if (!Array.isArray(values)) {
      values = [values];
    }
  } catch (e) {
    // Fallback: handle as comma-separated string
    values = arr.split(',');
  }

  return values.includes(val);
  }
}
