import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { CustomersService } from '../../../../shared/services/customers/customers.service';
import { LoaderService } from '../../../../shared/services/loader.service';

import { NgSelectModule } from '@ng-select/ng-select';
import { NgxMatIntlTelInputComponent } from 'ngx-mat-intl-tel-input';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-create-customer',
  templateUrl: './create-customer.component.html',
  styleUrls: ['./create-customer.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, NgSelectModule, NgxMatIntlTelInputComponent, FormsModule]
})
export class CreateCustomerComponent extends Unsub implements OnInit {
  public Password: any;
  public EmailError: any = false;
  public sendingResponse: { [key: string]: boolean } = {};
  isloader = true;
  data: any;
  constructor(
    private customersService: CustomersService,
    private toastr: ToastrService,
    private router: Router,
    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.Password = this.customersService.RandomPassWord();
    
    this.createCustomListFn();
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.createCustomListFn();

      },
    });
  }

  createCustomer(ngForm: any, buttonId) {
    
    const cf = this.customfield;
    const newCf = {};
    for (const i in cf) {
      const e = cf[i].val;
      newCf[i] = e;
    }

    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      
      const data = { ...ngForm.value, ...newCf };
      this.adminService
        .CreateCustomer(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.errors.message));
            }
          },
          error: () => {
             this.sendingResponse[buttonId] = false;
          },
        });
    }
  }

  createCustomListFn() {
    this.isloader = true;
    this.loaderService.showLoader();
    this.adminService
      .getCreateCustomer()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res: any) => {
          this.isloader = false;
          this.data = res;
          if (res?.customfields) {
            res.customfields.forEach((element) => {
              if (
                (element.fieldtypes == 'radio' ||
                  element.fieldtypes == 'checkbox') && element.status == 1
              ) {
                this.customfield['custom_' + element.id] = {
                  status: element.fieldrequired,
                };
                if (element.fieldrequired == 1) {
                  this.checkStatus = true;
                }
              }
            });
          }
          this.loaderService.hideLoader();
        },
        error: () => { this.isloader = true; this.loaderService.hideLoader() }
      }); 
  }


  customfield = {};
  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].status == 1) {
        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;
    }
  }

  ngOnInit(): void { }
}
