import { Message } from '@angular/compiler/src/i18n/i18n_ast';
import { ChangeDetectorRef, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { BsModalService } from 'ngx-bootstrap/modal';
import { DeviceDetectorService } from 'ngx-device-detector';
import { Subscription } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { AppService } from '../../../app.service';
import { IframeMsgHandlingService } from '../../../oneit/services/iframe-msg-handling.service';
import { MsgsService } from '../../../oneit/services/msgs.service';
import { UserService } from '../../../oneit/services/user.service';
import { UtilsService } from '../../../oneit/services/utils.service';
import { GoogleTagManagerService } from '../../../services/google-tag-manager.service';
import { AdminPortalLayoutService } from './admin-portal-layout.service';

@Component({
    selector: 'app-admin-portal-layout',
    templateUrl: './admin-portal-layout.component.html',
    styleUrls: ['./admin-portal-layout.component.scss']
})
export class AdminPortalLayoutComponent implements OnInit, OnDestroy {

    @ViewChild('reachedCapModal') reachedCapModal;
    @ViewChild('trialNotAllowedModal') trialNotAllowedModal;
    @ViewChild('jobNotSavedModal') jobNotSavedModal;
    showLoader: boolean;
    subscriptions: Array<Subscription> = [];
    successMsgs: Array<Message> = [];
    clientName: string;
    userName: string;
    homeURL: string;
    companyName: string;
    companyUser: any;
    selectedTeam: any;
    selectedTeamID: string;
    redirectURL: string;
    createJobDisabled: boolean;
    isStandardUser: boolean;
    hiringTeams: Array<any>;
    userMenu: any;
    sidebarMenu: any;
    select2Options = {
        minimumResultsForSearch: Infinity
    };
    showChat = false;
    showBubble = false;
    jobApplicationID: string;
    jobNotSaved: boolean = false;
    gotoURL: any;
    dataLayer: any;

    constructor(
        private deviceService: DeviceDetectorService,
        private msgsService: MsgsService,
        private userService: UserService,
        private adminPortalLayoutService: AdminPortalLayoutService,
        private utilsService: UtilsService,
        private appService: AppService,
        private titleService: Title,
        private router: Router,
        private modalService: BsModalService,
        private iframeMsgHandlingService: IframeMsgHandlingService,
        private changeDetector: ChangeDetectorRef,
        private googleTagManagerService : GoogleTagManagerService
    ) {
    }

    ngOnInit(): void {
        // Subscribe to msgReceived of iframeMsgHandlingService to get JobId
        this.subscriptions.push(this.iframeMsgHandlingService.msgReceived.subscribe(
            (message: any) => {
                if (!message || !message.name) {
                    return;
                }

                if (message.name === 'HiringTeamChat') {
                    if(!message.message) {
                        this.jobApplicationID = null;
                        this.showBubble = false;
                    } else {
                        const msg = JSON.parse(message.message);
                        this.jobApplicationID = msg.JobApplicationID;
                        // Show Chat bubble if message service allows
                        this.showBubble = true;
                    }
                } else if (message.name === 'HiringTeamChatIC') {
                    if(!message.message) {
                        this.jobApplicationID = null;
                        this.showChat = false;
                    } else {
                        const msg = JSON.parse(message.message);
                        this.jobApplicationID = msg.JobApplicationID;
                        // Show message popup if message service allows
                        this.showChat = true;
                        $('.hlp-checklist-button').focus();
                    }
                } else if (message.name === 'DisableCreateJobButton') {
                    if(message.message != this.createJobDisabled) {
                        this.createJobDisabled  = message.message;
                        this.changeDetector.detectChanges();
                    }
                } else if (message.name === 'EnableClientMenu') {
                    if (message.message === true) {
                        this.loadMenu();
                    }
                } else if (message.name === 'OnJobScreen') {
                    if(message.message != this.jobNotSaved) {
                        this.jobNotSaved  = message.message;
                        this.changeDetector.detectChanges();
                    }
                } else if (message.name === 'dataLayer') {
                    if(message.message != null) {
                        console.log(message.message[0]);
                        this.dataLayer = message.message[0];
                        console.log(message.message[0].userId); 
                        console.log(message.message[0].stripeId);
                        //todo change this code, and also call this when hiring team is modified
                        this.googleTagManagerService.pushTag({
                            userId: message.message[0].userId,
                            stripeId: message.message[0].stripeId
                        });
                    }
                }
            }
        ));

        if (this.deviceService.isMobile()) {
            window.location.href = `${environment.baseUrl}extensions/adminportal/responsive_alert.jsp`;
        }
        this.subscriptions.push(
            this.msgsService.successMsgsUpdated.subscribe(
                data => {
                    this.successMsgs = data;
                }
            )
        );

        this.titleService.setTitle('Matchd');
        this.subscribeToUserData();
        this.loadData();
    }

    onRouteUpdate(): void {
        this.loadData();
    }

    loadData(): void {
        this.userService.reloadUserDetails();
        this.msgsService.clearErrorMessages();

        this.adminPortalLayoutService.reloadAdminUserDetails();
        this.loadMenu();
        this.userName = this.userService.getUsername();
    }

    subscribeToUserData(): void {
        this.subscriptions.push(this.adminPortalLayoutService.userDataUpdated.subscribe(
            data => {
                this.clientName = data.ClientName || this.userService.getFullName();
                this.homeURL = data.HomeURL;
                this.companyName = data.CompanyName;
                this.companyUser = data.CompanyUser;
                this.selectedTeam = data.SelectedTeam;
                this.selectedTeamID = data.SelectedTeam ? data.SelectedTeam.ObjectID : null;
                this.hiringTeams = data.HiringTeams;
                this.createJobDisabled = data.CreateJobDisabled;

                if (this.hiringTeams) {
                    // this.utilsService.addNULLOptionForAssocSelect(this.hiringTeams, 'HiringTeamName');
                    for (const hiringTeam of this.hiringTeams) {
                        hiringTeam.id = hiringTeam.ObjectID;    // Added for select2
                        hiringTeam.text = hiringTeam.HiringTeamName;
                    }
                }

                if (this.companyName) {
                    this.titleService.setTitle(`Matchd - ${this.companyName}`);
                } else {
                    this.titleService.setTitle('Matchd');
                }
                // this.googleTagManagerService.pushTag({
                //     userId: 'ht001@matchd.com',
                //     stripeId: 'cus_EHGTq8xJ37buSh'
                // });
            },
            error => {
                this.utilsService.handleError(error);
            }
        ));
    }

    loadMenu(): void {
        this.adminPortalLayoutService.getAdminMenu()
            .subscribe(
                data => {
                    this.userMenu = data.userMenu;
                    this.sidebarMenu = data.sidebarMenu;
                },
                error => {
                    this.utilsService.handleError(error);
                }
            );
    }

    selectedTeamChanged(event: any): void {
        this.selectedTeamID = event.value;

        this.showLoader = true;
        this.subscriptions.push(
            this.adminPortalLayoutService.selectHiringTeam(this.selectedTeamID)
                .subscribe(
                    () => {
                        this.router.navigate(['admin/iframe-page', this.homeURL]);
                        this.loadData();
                        this.showLoader = false;
                    },
                    error => {
                        this.showLoader = false;
                        this.utilsService.handleError(error);
                    }
                )
        );
    }

    createJobClicked(): void {
        if(!this.createJobDisabled) {
            this.showLoader = true;
            this.subscriptions.push(
                this.adminPortalLayoutService.createJob(this.selectedTeamID, this.companyUser)
                    .subscribe(
                        data => {
                            if (data.AllowCreateJob) {
                                if (data.AllowCreateJob === 'REACHED_CAP') {
                                    this.modalService.show(this.reachedCapModal);
                                } else if (data.AllowCreateJob === 'TRIAL') {
                                    this.modalService.show(this.trialNotAllowedModal);
                                } else {

                                    this.router.navigate(['admin/iframe-page', data.redirectURL]);
                                }
                                this.isStandardUser = data.StandardUser;
                                this.redirectURL = data.redirectURL;
                                this.showLoader = false;
                            }
                        },
                        error => {
                            this.showLoader = false;
                            this.utilsService.handleError(error);
                        }
                    )
            );
        }
    }

    menuItemClick(routerURL): void {
        if (!(routerURL instanceof Array)) {
            routerURL = ['/admin/' + routerURL];
        }

        if (this.jobNotSaved) {
            this.gotoURL = routerURL;
            this.modalService.show(this.jobNotSavedModal);
        } else {
            this.router.navigate(routerURL);
        }
    }

    closeJobNotSavedPopup() {
        this.modalService.hide(1);
    }

    gotoNextPage() {
        this.modalService.hide(1);
        this.jobNotSaved = false;
        this.router.navigate(this.gotoURL);
    }

    minimizeWindow(response: any): void {
        this.showChat = false;

        this.iframeMsgHandlingService.postMessage(response);
    }

    ngOnDestroy(): void {
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}
