// Angular Core
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Subscription } from 'rxjs';

// Interfaces
import { GetStatesInterface } from 'src/app/interfaces/get-states-interface';
import { ModalConfig } from 'src/app/interfaces/common-interfaces';
import { AuthorizedStatesService } from 'src/app/services/authorizedStates/authorized-states.service';

import { AuthStateLicenseUploadModalComponent } from './auth-state-licnese-upload-modal/auth-state-license-upload-modal.component';
import { DeleteAuthStateLicenseModalComponent } from './delete-auth-state-license-modal/delete-auth-state-license-modal.component';
import { NgbModal, NgbModalConfig, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; 

interface STAllinterface {
  clickAllFlag: number | boolean;
  activeTab: string;
}

interface STValuesinterface {
  value: string, 
  check: number | boolean, 
  activeTab: string
}
@Component({
  standalone: false,
  selector: 'app-auth-states',
  templateUrl: './auth-states.component.html',
  styleUrls: ['./auth-states.component.scss']
})
export class AuthStatesComponent implements OnInit {

  @Input() sortedStates!:GetStatesInterface['data'][0][][];
  @Input() activeTab!:string;
  @Input() authStatesConfig!:any;
  @Input() rxStates!:GetStatesInterface['data'][0][][];
  @Input() stateCheckboxes!: any[];
  @Input() authLicenseVars!:any;
  @Input() isAdmin!: boolean;
  @Output() statesTab = new EventEmitter<number>();
  @Output() STAllData = new EventEmitter<STAllinterface>();
  @Output() STValuesData = new EventEmitter<STValuesinterface>();

  constructor(private modalService: NgbModal, private authorizedStatesService : AuthorizedStatesService) { }

  ngOnInit(): void {
  }

  /**
   * Emit the STValuesData event to pass the data to the parent component
   * @param {string} value 
   * @param {number | boolean} check 
   * @param {string} activeTab 
   */
  callcheckUncheckSTValuesFunc(value: string, check: number | boolean, activeTab: string){
    const STValuesData = {
      value: value,
      check: !check,
      activeTab: activeTab
    }
    this.STValuesData.emit(STValuesData);
  }

  /**
   * Emit the STAllData event to pass the data to the parent component
   * @param {boolean | number} clickAllFlag 
   * @param {string} activeTab 
   */
  callcheckOrUncheckSTAllFunc(clickAllFlag: boolean | number, activeTab: string){
    const STAllData = {
      clickAllFlag: !clickAllFlag,
      activeTab: activeTab
    };
    this.STAllData.emit(STAllData)
  }

   authTypes = {authStates : 'rx' , controlStates: 'control', otcStates: 'otc'};

   /**
   * Private property to set the status of licenseUploadModal
   * @type boolean
   */
  licenseUploadModalOpened: boolean = false;
                
  /*
   * Private property to set the base modal config
   * @type Object
   */
  licenseUploadModalConfig: ModalConfig = {
      showHeader: true,
      title: "",
      class: 'authStateLicenseModal',
      minWidth: '1000px'
  };

   /**
    * Method to open Modal popup to upload license document
    * @param string stateName
    * @param string stateCode
    * @param string authType
    * @returns void
   */
  licenseUploadModal!: NgbModalRef;
  openStateLicenseModal(stateName: string, stateCode: string, authType: string) {
    this.licenseUploadModal = this.modalService.open(AuthStateLicenseUploadModalComponent, {size: 'sm'});
    this.licenseUploadModal.componentInstance.licenseUploadModal = this.licenseUploadModal;
    this.licenseUploadModal.componentInstance.stateName = stateName;
    this.licenseUploadModal.componentInstance.stateCode = stateCode;
    this.licenseUploadModal.componentInstance.authType = (this.authTypes as any)[authType];
    this.licenseUploadModal.componentInstance.licenseExpirationDate = "";
    this.licenseUploadModal.componentInstance.step1 = 'rsh-active';
    this.licenseUploadModal.componentInstance.step2 = '';
    this.licenseUploadModal.componentInstance.step3 = '';
    this.licenseUploadModal.componentInstance.showStatusMsg = false;
    this.licenseUploadModal.componentInstance.statusMsg = "";
    this.licenseUploadModal.componentInstance.licenseUploadClickOk = () => {
        this.licenseUploadClickOk();
        this.statesTab.emit(1);
    };
    this.licenseUploadModal.componentInstance.licenseUploadClickCancel = this.licenseUploadClickCancel;
    this.licenseUploadModal.shown.subscribe(() => {
      this.licenseUploadModalOpened = true;
    });

    this.licenseUploadModal.closed.subscribe(() => {
      this.licenseUploadModalOpened = false;
    });
  };

  /**
   * Public method click ok in refrigerated modal
   */
  licenseUploadClickOk() {
    this.licenseUploadModal.close('ok');
  };

  /**
   * Public method click ok in refrigerated modal
   */
  licenseUploadClickCancel() {
    this.licenseUploadModal.close('cancel');
  };

   /*
  * Private Property for base modal config for deleteLicenseModal
  */
   deleteLicenseModalConfig:ModalConfig = {
    showHeader: false,
    title: ""
  };

  /**
   * Private method to show the document delete confirmation modal
   * @param int stateId
   * @param string authType
   * @returns void
   */
  deleteLicenseModalSub!:NgbModalRef;
  showDeleteLicenseModal(stateId: number, authType: string) {
      this.deleteLicenseModalConfig.title = "";
      this.deleteLicenseModalSub = this.modalService.open(DeleteAuthStateLicenseModalComponent, {size: 'sm'});
      this.deleteLicenseModalSub.componentInstance.deleteLicenseModalSub = this.deleteLicenseModalSub;
      this.deleteLicenseModalSub.componentInstance.authstateId = stateId;
      this.deleteLicenseModalSub.componentInstance.licenseAuthType = (this.authTypes as any)[authType];
      this.deleteLicenseModalSub.componentInstance.deleteLicenseModalClose = () => {
        this.deleteLicenseModalClose();
        this.statesTab.emit(1);
      };
  };

   /*
   * Method to close delete confirmation modal
   */
   deleteLicenseModalClose() {
       this.deleteLicenseModalSub.close('ok');
   };

   /**
    * Method validate State license document
    * @param int stateId
    * @param string authType
    * @returns void
   */
    validaeLicenseSubscribe!: Subscription;
    validateLicenseDoc(stateId: number, authType: string) {
        var updateData = {
          'state_id'  : stateId,
          'auth_type' : (this.authTypes as any)[authType]
        };
        this.validaeLicenseSubscribe = this.authorizedStatesService.validateLicenseDoc(updateData)
            .subscribe({
             next: () => {
               this.statesTab.emit(1);
             },
             error: (err) => {
               this.authorizedStatesService.errorCallBack(err);
             },
             complete: () => { },
        })
    };

  // Trackby function for track looping items
  trackByFn(index:number, item: any){
    if (item.length > 0 && item[0]?.stateId) {
        return item[0].stateId;
    }
    return index;
  }

}