import { Component, ElementRef, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { FormBuilder, FormGroup, FormsModule, NgForm } from '@angular/forms';
import { HttpHeaders } from '@angular/common/http';
import Swal from 'sweetalert2';
import { takeUntil } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipe } from '@ngx-translate/core';
import { AngularEditorConfig, AngularEditorModule } from '@kolkov/angular-editor';
import { Unsub } from '../../../../shared/class/unsub.class';
import { adminToolbar } from '../../../../shared/data/editortoolbar';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { GeneralSettingsService } from '../../../../shared/services/admin/general-settings.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { NavService } from '../../../../shared/services/nav.service';
import { CommonModule } from '@angular/common';
import { NgSelectModule } from '@ng-select/ng-select';
import { ColorPickerModule } from 'ngx-color-picker';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { TimerService } from '../../../../shared/services/timer.service';
import { TimeoutGuard } from '../../../../shared/guard/timeout.guard';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { MaxLengthValidatorDirective } from '../../../../shared/directives/max-length-validator.directive';
import moment from 'moment-timezone';
import { ClipboardModule, ClipboardService, IClipboardResponse } from 'ngx-clipboard';

@Component({
  selector: 'app-general-setting',
  templateUrl: './general-setting.component.html',
  styleUrls: ['./general-setting.component.scss'],
  standalone: true,
  imports: [CommonModule, AdminPageHeaderComponent, TranslatePipes, AngularEditorModule, NgSelectModule, ColorPickerModule, RouterLink, FormsModule, MaxLengthValidatorDirective, ClipboardModule]
})
export class GeneralSettingComponent extends Unsub implements OnInit {
  timezone;
  timezones;
  croncommanddata;
  public primaryColorToggle: boolean = false;
  public secondaryColorToggle: boolean = false;
  @ViewChild('contactemail', { static: false }) contactemail!: ElementRef;
  public sendingResponse: { [key: string]: boolean } = {};
  colorprimary;
  colorsecondary;
  localStorageLang;
  toolbar: AngularEditorConfig = adminToolbar;
  dateList = [
    { id: 1, value: 'd M, Y' },
    { id: 2, value: 'd MMM, yy' },
    { id: 3, value: 'M.d.y' },
    { id: 4, value: 'Y-M-d' },
    { id: 5, value: 'dd-M-Y' },
    { id: 6, value: 'd/M/y' },
    { id: 7, value: 'y/M/d' },
  ];
  timeList = [
    { id: 1, name: '03:00 PM', value: 'h:mm a' },
    { ia: 2, name: '03:00:02 PM', value: 'h:mm:ss a' },
    { id: 3, name: '15:00', value: 'HH:mm' },
    { id: 4, name: '15:00:02', value: 'HH:mm:ss' },
  ];
  weekList = [
    { id: 1, name: 'Sunday', value: '0' },
    { id: 2, name: 'Monday', value: '1' },
    { id: 3, name: 'Tuesday', value: '2' },
    { id: 4, name: 'Wednesday', value: '3' },
    { id: 5, name: 'Thursday', value: '4' },
    { id: 6, name: 'Friday', value: '5' },
    { id: 7, name: 'Saturday', value: '6' },
  ];
  form: FormGroup;
  form1: FormGroup;
  form2: FormGroup;
  form3: FormGroup;
  form4: FormGroup;
  response: any;
  response2: any;
  setting;
  constructor(
    public generalSettingsService: GeneralSettingsService,
    private toastr: ToastrService,
    public fb: FormBuilder,
    public navServices: NavService,
    private adminService: AdminService,
    private timeoutGuard: TimeoutGuard,
    private router: Router,
    private route: ActivatedRoute,
    private _clipboardService: ClipboardService,
    private timerService: TimerService,
    private modalService: NgbModal,
    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.form = this.fb.group({
      image: null,
    });
    this.form1 = this.fb.group({
      image: null,
    });
    this.form2 = this.fb.group({
      image: null,
    });
    this.form3 = this.fb.group({
      image: null,
    });
    this.form4 = this.fb.group({
      image: null,
    });
    this.toolbar.placeholder = this.translate.transform('Enter Your Text...');

    this.timezones = moment.tz.names();
  }
  ResponceProfile;
  languagesList;
  selectedLanguage;
  ngOnInit(): void {
    if (localStorage.getItem('lang')) {
      this.localStorageLang = localStorage.getItem('lang');
    }

    this.generalSetting();
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: () => {
        this.generalSetting();
      },
    });
    this.handleClipboardResponse();
  }
  handleClipboardResponse() {
    this._clipboardService.copyResponse$.subscribe((res: IClipboardResponse) => {
      if (res.isSuccess) {
        this.toastr.success(this.translate.transform("Copied"))
      }
    });
  }
  public timeZoneChanged(timeZone: string): void {
    this.timezone = timeZone;
  }

  generalSetting = () => {
    this.loaderService.showLoader();
    this.generalSettingsService
      .index()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (ele) => {
          this.ResponceProfile = ele;
          this.croncommanddata = ele.croncommanddata;
          this.Src = ele?.title?.logoimage;
          this.Src1 = ele?.title?.logoimage1;
          this.Src2 = ele?.title?.logoimage2;
          this.Src3 = ele?.title?.logoimage3;
          this.Src4 = ele?.title?.logoimage4;

          this.setting = ele.setting?.original;
          this.timezone = this.setting?.default_timezone;

          this.colorprimary = this.setting?.theme_color;
          this.colorsecondary = this.setting?.theme_color_dark;
          this.languagesList = ele.languages;
          this.selectedLanguage = ele.setting?.original?.default_lang;
          this.loaderService.hideLoader();
        },
        error: () => this.loaderService.hideLoader()
      });
  };
  public Src: any;
  public Src1: any;
  public Src2: any;
  public Src3: any;
  public Src4: any;
  public File: any;

  image(event: any) {
    const file = (event.target as HTMLInputElement)?.files?.[0];
    this.form.patchValue({
      image: file,
    });
  }

  image1(event: any) {
    // this.File = event.target.files[0].name
    const file = (event.target as HTMLInputElement)?.files?.[0];
    this.form1.patchValue({
      image: file,
    });
  }

  image2(event: any) {
    // this.File = event.target.files[0].name
    const file = (event.target as HTMLInputElement)?.files?.[0];
    this.form2.patchValue({
      image: file,
    });
  }

  image3(event: any) {
    // this.File = event.target.files[0].name
    const file = (event.target as HTMLInputElement)?.files?.[0];
    this.form3.patchValue({
      image: file,
    });
  }

  image4(event: any) {
    // this.File = event.target.files[0].name
    const file = (event.target as HTMLInputElement)?.files?.[0];
    this.form4.patchValue({
      image: file,
    });
  }
  AppTitleandLogos(ngform: NgForm, buttonId) {
    if (ngform.valid) {
      this.sendingResponse[buttonId] = true;
      const formData: any = new FormData();
      formData.append('title', ngform.value.title);
      formData.append('id', ngform.value.id);
      formData.append('image', this.form.controls['image'].value);
      formData.append('image1', this.form1.controls['image'].value);
      formData.append('image2', this.form2.controls['image'].value);
      formData.append('image3', this.form3.controls['image'].value);
      formData.append('image4', this.form4.controls['image'].value);

      const httpOptions = {
        headers: new HttpHeaders({
          Accept: 'application/json',
        }),
      };

      this.generalSettingsService.store(formData, httpOptions)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.form.reset({});
              this.form1.reset({});
              this.form2.reset({});
              this.form3.reset({});
              this.form4.reset({});
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
    }
  }
  invoiceSettingFn(ngform: NgForm, buttonId) {

    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .ticketsettingInvoiceAddress(ngform.value)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  contact(ngform: NgForm, buttonId) {
    //
    const data = {
      "CONTACT_ENABLE": ngform.value.CONTACT_ENABLE,
      "contact_form_mail": ngform.value.contact_form_mail,
    };
    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .contactUs(data)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  UrlSet(data: NgForm, buttonId) {
    if (data.valid) {
      const PostData = {

        "terms_url": data.value.terms_url,
      };
      this.sendingResponse[buttonId] = true;
      this.generalSettingsService
        .urlset(PostData)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
    }
  }
  colorSetting(data: NgForm, buttonId) {
    if (data.valid) {
      const PostData = {
        "theme_color": data.value.theme_color,
        "theme_color_dark": data.value.theme_color_dark,
      };
      this.sendingResponse[buttonId] = true;
      this.generalSettingsService
        .frontendStore(PostData)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
    }
  }
  globalLanguageSetting(data: any, buttonId) {
    const PostData = {
      "default_lang": data.default_lang,
    };
    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .languagesettingstore(PostData)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  globalDateTimeFormat(data: any, buttonId) {
    //
    const PostData = {
      "date_format": data.date_format,
      "time_format": data.time_format,
    };
    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .datetimeformatstore(PostData)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  firstDayoftheWeek(data: any, buttonId) {
    //
    const PostData = {
      "start_week": data.start_week,
    };
    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .startweekstore(PostData)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  globalTimezones(data: any, buttonId) {
    const PostData = {

      timezones: data.timezones,
    };
    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .timezoneupdate(PostData)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  footerCopyrightText(data: any, buttonId) {
    const PostData = {
      copyright: data.copyright,
      id: this.ResponceProfile.footertext.id,
    };
    this.sendingResponse[buttonId] = true;
    this.generalSettingsService
      .footerstore(PostData)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
  }
  businesslogodelete(id: any, type: any, ele: any) {
    const PostData = {
      logo: type,
      id: id,
    };
    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure ?'),
      text: this.translate.transform('Your will not be able to recover this imaginary file!'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      confirmButtonText: this.translate.transform('Yes, delete it!'),
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.adminService
          .logodelete(PostData)
          .pipe(takeUntil(this.unSubscribe$))
          .subscribe({
            next: (res) => {
              ele.value = '';
              Swal.fire({
                title: this.translate.transform('Deleted'),
                text: this.translate.transform(res.success),
                icon: 'success',
                confirmButtonColor: '#6259ca',
              });
            },
          });
      }
    });
  }
  GlobalSettings(ngform: NgForm) {
    const data = ngform.value;

    this.generalSettingsService.GlobalSettings(data).subscribe({
      next: (res) => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
        if (res?.error) {
          this.toastr.error(this.translate.transform(res.error));
        }
      }
    });
  }
  knowledgeForm(ngform?) {
    let data = {};
    if (ngform) {
      data = ngform.value;
    }
    else {
      data['KNOWLEDGE_ENABLE'] = this.setting?.KNOWLEDGE_ENABLE == 'yes' ? true : false;
      data['FAQ_ENABLE'] = this.setting?.FAQ_ENABLE == 'yes' ? true : false;
    }
    this.generalSettingsService.kNOWLEDGEENABLESettings(data).subscribe({
      next: (res) => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    });
  }
  profileuser(ngform) {
    const data = ngform.value;
    this.generalSettingsService.profileuser(data).subscribe({
      next: (res) => {
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      }
    });
  }
  twoFactorAuthentication(ngform, buttonId) {
    const data = ngform.value;

    this.sendingResponse[buttonId] = true;
    this.generalSettingsService.twoFactorAuthSetting(data).subscribe({
      next: (res) => {
        this.sendingResponse[buttonId] = false;
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      },
      error: () => {
        this.sendingResponse[buttonId] = false;
      },
    });
  }
  customerprofiledelete(ngform, buttonId) {
    const data = ngform.value;

    this.sendingResponse[buttonId] = true;
    this.generalSettingsService.customerprofiledelete(data).subscribe({
      next: (res) => {
        this.sendingResponse[buttonId] = false;
        if (res?.success) {
          this.toastr.success(this.translate.transform(res.success));
        }
      },
      error: () => {
        this.sendingResponse[buttonId] = false;
      },
    });
  }
  closeResult = '';

  open(content) {
    this.modalService
      .open(content, { backdrop: 'static', keyboard: false })
      .result.then((result) => {
        this.closeResult = `Closed with: ${result}`;
      });
  }

  ChangeTheValues(res, buttonId) {
    if (res.valid) {
      const PostData = {

        name: res.value?.name,
      };

      this.sendingResponse[buttonId] = true;
      this.generalSettingsService.logindisable(PostData).subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
        },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      });
    }
  }

  securitySettingFn(ngform: NgForm, buttonId) {
    if (ngform.valid) {
      this.sendingResponse[buttonId] = true;
      const data = ngform.value;

      this.generalSettingsService.securitySettings(data).subscribe({
        next: res => {
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));
          }
          this.sendingResponse[buttonId] = false;
        },
        error: () => this.sendingResponse[buttonId] = false
      });
    }
  }
  sessionFn(ngform: NgForm, buttonId) {
    if (ngform.valid) {
      this.sendingResponse[buttonId] = true;
      const data = ngform.value;

      this.generalSettingsService.customerautologout(data).subscribe({
        next: res => {
          if (res?.success) {
            this.toastr.success(this.translate.transform(res.success));

            if (data?.admin_users_inactive_auto_logout) {
              let gurad$: any = this.timeoutGuard.canActivate(this.route.snapshot, this.router.routerState.snapshot)
              gurad$.subscribe();
            } else {
              this.timerService.stopInnerTimer();
              this.timerService.stopTimer();
            }
          }
          this.sendingResponse[buttonId] = false;
        },
        error: () => this.sendingResponse[buttonId] = false
      });
    }
  }

  public primaryColor(data: any): void {
    this.colorprimary = data.color;
  }
  public secondaryColor(data: any): void {
    this.colorsecondary = data.color;
  }


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