import { CommonModule } from '@angular/common';
import { ChangeDetectorRef, Component } from '@angular/core';
import { TextInputComponent } from '../../../../core/components/input/text-input/text-input.component';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { TextareaInputComponent } from '../../../../core/components/input/textarea-input/textarea-input.component';
import { CheckBoxInputComponent } from '../../../../core/components/input/check-box-input/check-box-input.component';
import { LiveChatService } from '../../../../shared/services/admin/livechat.service';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from '@ngx-translate/core';
import { SelectInputComponent } from '../../../../core/components/input/select-input/select-input.component';
import { NgSelectInputComponent } from '../../../../core/components/input/ng-select-input/ng-select-input.component';
import { NumberInputComponent } from '../../../../core/components/input/number-input/number-input.component';
import { Unsub } from '../../../../shared/class/unsub.class';
import { LoaderService } from '../../../../shared/services/loader.service';
import { takeUntil } from 'rxjs';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { FileInputComponent } from '../../../../core/components/input/file-input/file-input.component';
import { RouterLink } from '@angular/router';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { ClipboardModule, ClipboardService, IClipboardResponse } from 'ngx-clipboard';

@Component({
  selector: 'app-livechat-settings',
  standalone: true,
  imports: [CommonModule, TranslatePipes, TextInputComponent, TextareaInputComponent, FileInputComponent, CheckBoxInputComponent, NumberInputComponent, NgSelectInputComponent, SelectInputComponent, RouterLink, ReactiveFormsModule, AdminPageHeaderComponent, ClipboardModule],
  templateUrl: './livechat-settings.component.html',
  styleUrl: './livechat-settings.component.scss'
})
export class LivechatSettingsComponent extends Unsub {
  data;
  domainname;
  setting;
  url = "";
  livechatPath = '';
  public sendingResponse: { [key: string]: boolean } = {};
  public fileResposne: { [key: string]: any } = {};
  notificationPlayTypeList = ['Loop', 'Single'];
  iveChatPositionList = ['right', 'left'];
  liveChatIconSizeList = ['small', 'large'];
  liveChatFlowloadList = ['Every 24 hours', 'For a single unique user'];
  tagslist: any = null;
  initailSelect: any[] | null = [];
  initailSelectAgentlivechatFileUploadTypes: any[] | null = [];
  initailSelectlivechatFeedbackDropdown: any;
  constructor(private liveChatService: LiveChatService, private toastr: ToastrService, private translate: TranslatePipe, loaderService: LoaderService, private adminService: AdminService, private _clipboardService: ClipboardService) {
    super(loaderService);
    this.tagslist = [];
    this.liveChatFn();
    this.adminService.RefreshRquestAdmin$.pipe(
      takeUntil(this.unSubscribe$)
    ).subscribe({
      next: (res) => {
        this.liveChatFn();
      },
    });
    this.url = location.origin + document.querySelector('base')?.getAttribute('href');
    this.handleClipboardResponse();
  }
  handleClipboardResponse() {
    this._clipboardService.copyResponse$.subscribe((res: IClipboardResponse) => {
      if (res.isSuccess) {
        this.toastr.success(this.translate.transform("Copied"))        
      }
    });
  }
  liveChatFn() {

    this.loaderService.showLoader();
    // this.isloader = true;
    this.liveChatService.livechatSettings()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.data = res;
          this.setting = res.settings;
          this.domainname = res.domainname;
          this.initailSelect = this.setting?.livechatFileUploadTypes ? this.convertToArray(this.setting.livechatFileUploadTypes) : null
          this.initailSelectAgentlivechatFileUploadTypes = this.setting?.AgentlivechatFileUploadTypes ? this.convertToArray(this.setting.AgentlivechatFileUploadTypes) : null
          this.initailSelectlivechatFeedbackDropdown = this.setting?.livechatFeedbackDropdown ? this.convertToArray(this.setting.livechatFeedbackDropdown) : null;
          // Assuming `sslcertificate` and `sslkey` are properties in `res.settings`
          this.livechatssldstore.patchValue({
            'sslcertificate': this.setting.serversslcertificate,
            'sslkey': this.setting.serversslkey,
          });

          this.livechatCredentials.patchValue({
            'liveChatPort': this.setting.liveChatPort,
            'liveChat_hidden': this.setting?.liveChatHidden == 'false' ? true : false,
          });
          this.livechatPath = `<script src='${this.domainname}/assets/livechat/liveChat.js' wsPort='${this.setting?.liveChatPort}' domainName='${this.domainname}' defer></script>`
          this.loaderService.hideLoader();
        },
        error: err => this.loaderService.hideLoader()
      })
  }
  convertToArray(value: string): any[] {
    // Trim any leading or trailing whitespace
    value = value.trim();

    // Check if the string starts and ends with square brackets
    if (value.startsWith('[') && value.endsWith(']')) {
      // Try parsing the string as a JSON array
      try {
        return JSON.parse(value);
      } catch (error) {
        console.error('Error parsing JSON:', error);
        return []; // Return an empty array if parsing fails
      }
    } else {
      // If the string is not a JSON array, split it by commas and trim each value
      return value.split(',').map(item => item.trim());
    }
  }


  FileSettings = new FormGroup({});
  agentLiveChat = new FormGroup({});
  feedBack = new FormGroup({});
  livechatAutoDelete = new FormGroup({});
  LivechatCustWelcome = new FormGroup({});
  livechatAutoSave = new FormGroup({});
  liveChatNotification = new FormGroup({});
  liveChatNotificationsound = new FormGroup({});
  liveChatIconSetting = new FormGroup({
    delete_icon: new FormControl(false)
  });
  livechatCredentials = new FormGroup({
    'liveChatPort': new FormControl(),
    'liveChat_hidden': new FormControl(),
  });
  livechatssldstore = new FormGroup({
    'sslcertificate': new FormControl(),
    'sslkey': new FormControl(),
  });
  operatorsNotifications = new FormGroup({});
  livechat = new FormGroup({});
  livechatIconSize = new FormGroup({});
  liveChatPosition = new FormGroup({});
  liveChatFlowload = new FormGroup({});
  LiveChatSettings(name, main) {
    if (name.valid) {
      let formData = new FormData();
      for (const key in name.value) {
        if (name.value.hasOwnProperty(key) && !this.fileResposne[key]) {
          formData.append(key, name.value[key]);
        }
        if (this.fileResposne[key]) {
          formData.append(key, this.fileResposne[key])
        }
      }
      this.liveChatService[main](formData).subscribe({
        next: res => {
          if (res?.success) {
            if(main == "livechatLiveChatIconSound" || main == "livechatLiveChatNotificationsSound"){
              name.reset();
            }
            this.toastr.success(this.translate.transform(res.message ?? res.success));
          }
        }
      })
    }
  }
  handlePatchValue(patchValueData: any, group, name) {
    this.fileResposne[name] = patchValueData;
  }

  deleteIconFlag = false;

  deleteIcon() {
    const confirmed = confirm('Are you sure you want to delete this icon?');
    if (confirmed) {
      // Set the delete_icon value to true before reset
      this.liveChatIconSetting.get('delete_icon')?.setValue(true);
      this.deleteIconFlag = true;  // Update flag for internal tracking
    }
  }
}
