// Angular Core
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormGroup, ControlContainer } from '@angular/forms';

// Components
import { StoreInfoComponent } from '../store-info.component';

// Interfaces
import { SuppliersList } from 'src/app/interfaces/supplier/suppliers-list';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { GetStates } from 'src/app/interfaces/user/get-states';

@Component({
  standalone: false,
  selector: 'app-references-tab',
  templateUrl: './references-tab.component.html',
  styleUrls: ['./references-tab.component.scss']
})
export class ReferencesTabComponent implements OnInit {

    @Input() userStoreInfoForm: any = FormGroup;
    @Input() phnValidationMsg: string = '';
    @Input() generalValidationMsg: string = '';
    @Input() selectBoxValidationMsg: string = '';
    @Input() session!: SessionDataInterface['data'];
    @Input() states!: GetStates['data'];
    @Input() pmsList: any;
    @Input() suppliersList!: SuppliersList['data'];
    @Input() groupedSuppList!: any[];

    @Input() isReferencesCollapsed: boolean = true;
    @Output() isReferencesCollapsedChange = new EventEmitter<boolean>();
    userType: string = '';
    userPermissionArray: string[] = ['Wholesaler', 'Manufacturer'];

    @Output() update_user_data = new EventEmitter<string>();
    updateUserData(userEleName: string) {
        this.update_user_data.emit(userEleName);
    }
    @Output() check_for_other_option = new EventEmitter<string>();
    checkForOtherOption(type: string) {
        this.check_for_other_option.emit(type);
    }
    @Output() update_pms_value = new EventEmitter<{ pmsValue: string, pmsEleName: string }>();
    updatePMSValue(pmsValue: string, pmsEleName: string) {
        this.update_pms_value.emit({ pmsValue, pmsEleName });
    }

    constructor(private controlContainer: ControlContainer, public storeInfo: StoreInfoComponent) { }

    ngOnInit(): void {
        this.userStoreInfoForm = <FormGroup>this.controlContainer.control;
        this.userType = this.session.user_type;
    }

    get userStoreInfoFormData() { return this.userStoreInfoForm.controls; }

    /**
     * Autopopulate state and phone for primary and secondary suppliers
     * @param {string} vendorRefType
     * @returns {undefined}
     */
    populateSupplierDetails(vendorRefType: string) {
        var refId = this.userStoreInfoForm[vendorRefType + '_reference_id']?.value;
        this.suppliersList.forEach((supplier: SuppliersList['data'][0]) => {
            if (supplier.id === refId) {
                this.userStoreInfoForm[vendorRefType + '_reference_state'].value = supplier.stateCode;
                this.userStoreInfoForm[vendorRefType + '_reference_phone'].value = supplier.phone;
                return;
            }
        });
    };


    collapseTab() {
        this.isReferencesCollapsedChange.emit(!this.isReferencesCollapsed);
    }

}
