// Angular Core
import { Component, Input, OnInit, Output, EventEmitter, SimpleChanges, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

// RxJs
import { Subscription } from 'rxjs';

// Services
import { SearchService } from 'src/app/services/search/search.service';
import { SessionService } from 'src/app/services/session/session.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';

// Interfaces
import { CategoriesDataInterface } from 'src/app/interfaces/user/categories-data-interface';

@Component({
  standalone: false,
    selector: 'app-search-form',
    templateUrl: './search-form.component.html',
    styleUrls: ['./search-form.component.scss']
})
export class SearchFormComponent implements OnInit, OnDestroy {
    /**
     * NDC specific checkbox model
    */
    ndcSpecific: any = {
        checked: false
    };
    /**
     * search type passed for main search type ahead
    */
    typeaheadSearch = {
        searchtype: 'search'
    };

    clearSearchInputListner!: Subscription;
    searchTermListener!: Subscription;
    setNDCSpecificListener!: Subscription;
    getCategoriesSubscription!: Subscription;

    constructor(
        private searchService: SearchService,
        private router: Router,
        private sessionService: SessionService,
        private localStorageService: LocalStorageService
    ) { }

    ngOnInit(): void {
        /**
         * Event listener for searchTerm
         */
        this.searchTermListener = this.searchService.setSearchInput.subscribe((data: string) => {
            this.input = false;
        });
        /**
         * Event listener for ndcSpecific
         */
        this.setNDCSpecificListener = this.searchService.setNDCSpecific.subscribe({
            next: (data: any) => {
               this.ndcSpecific.checked = data === 'true';
            }
        });
        this.clearSearchInputListner = this.searchService.clearSearchInput.subscribe((data: boolean) => {
            this.input = true;
        });
        this.getCategories();
        this.setNDCSpecific();
        this.getSearchTerm();
    }


    ngOnChanges(changes: SimpleChanges): void {
    }

    @Input() directUrlCategories!: string[];
    @Output() directUrlCategoriesChange = new EventEmitter<any>();
    @Output() categoryMenuChange = new EventEmitter<any>();

    categoryMenuChangeOnEmit(data: CategoriesDataInterface['data']['categories']['categoryMenu']) {
        this.categoryMenuChange.emit(data)
    }

    getDirectUrlCategoriesOnEmit(data: string[]) {
        this.directUrlCategoriesChange.emit(data)
    }
    
    getCategories() {
        this.getDirectUrlCategoriesOnEmit(this.searchService.getDirectUrlCategories());
        this.getCategoriesSubscription = this.searchService.getCategories()
            .subscribe({
                next: (res: CategoriesDataInterface) => {
                  this.categoryMenuChangeOnEmit(res.data.categories.categoryMenu);
                },
                error: (err) => {
                  this.searchService.errorCallBack(err);
                }
            });
    }

    /**
     * returns true if search is being done from search controller
     * @returns {boolean}
     */
    isSearchPage() {
        return this.router.url?.startsWith('/market/search');
    };

    /**
     * Checks if input is an NDC after removing '-'
     * @param {string} value
     * @returns {boolean}
     */
    isNDCNumber(value: string) {
        let term: any = parseInt(value.replace('-', ''));

        if (isNaN(term)) {
            term = value;
        }
        return typeof (term) === 'number';
    };

    /**
     * Unchecks NDC Specific if non NDC input and saves to seach service
     * @returns {undefined}
     */
    setNDCSpecific() {
        var searchInput = this.searchService.getSearchTerm();
        if (!this.isNDCNumber(searchInput)) {
            this.ndcSpecific.checked = false;
        }
        if (this.localStorageService.getItem('ndc_specific_search_only') === 'true') {
            this.ndcSpecific.checked = true;
        }
        this.searchService.setNdcSpecific(this.ndcSpecific.checked);
    };

    /**
     * Method to conduct a search and render results
     * @returns {undefined}
     */
    search() {
        //user clicked go, this is a new search so we reset all filters and other options
        const search = this.searchService;
        search.setCategoryCode('All');
        var searchInput = search.getSearchTerm();
        var catCode = search.getCategoryCode();
        if (!search.searchLabel.includes(searchInput)) {
            search.searchLabel = '';
        }
        var label = search.searchLabel;

        search.resetSearchQuery();
        search.setSearchTerm(searchInput);
        this.setNDCSpecific();
        if (!search.resetNDCSpecific) {
            if (label !== '') {
                this.ndcSpecific.checked = false;
            }
        }

        //check if its a redirect search or a seach page search
        let isMySearchPage = this.isSearchPage();
        // var myUrl = '/market/search?searchLabel=' + escape(label) + '&searchTerm=' + escape(searchInput) + '&catCode=' + escape(catCode) + '&NDCSpecific=' + escape(this.ndcSpecific.checked);
        if (searchInput.length >= search.minInputLength) {
            //No need to reload the page if we search from search controller.
            if (isMySearchPage) {
                //Initiate search by emitting the search event.

                // TODO : when search component is implemented
                this.searchService.searchBySearchQuery.emit({ resetFilters: true });
            }
            /*
             * update url if we are in search page or navigate to search page
             * if search is done from a different page.
             */
            this.router.navigate(["/market/search"], { queryParams: { searchLabel: encodeURIComponent(label), searchTerm: searchInput, catCode: encodeURIComponent(catCode), NDCSpecific: encodeURIComponent(this.ndcSpecific.checked), page: 1 } });
        }
    };


    /**
     * Helper for links
     * @todo This method must be removed once multi search page is converted to Nova. This method is only to
     * navigate to multi search page.
     * @param {string} path
     * @returns {undefined}
     */
    go(path: string) {
        window.location.href = "https://" + window.location.hostname + path;
    };

    input: boolean = true;

    hideControlsBtn() {
        return this.sessionService.getHideControl();
    };

    /**
     * Check if the user is a GPO member and show brands or GPO deals based on that
     * @returns {unresolved}
     */
    checkIfGpoMember() {
        return this.sessionService.isGpoMember();
    };

    onsearchBySearchFormEmit(data: any) {
        this.search();
    }

    onshowClearSignEmit(data: any) {
        this.input = false;
    }

    onhideClearSignEmit(data: any) {
        this.input = true;
    }

    clearField() {
        this.searchService.clearSearchInput.emit(false);
        this.input = true;
        this.searchService.resetAllToInitialState();
    };

    getSearchTerm() {
        var searchInput = this.searchService.getSearchTerm();
        var pathArray = location.pathname.split('/');
        var pageName = pathArray[2];
        if (searchInput && pageName === 'search') {
            this.input = false;
        }
    };

    ngOnDestroy(): void {
        this.clearSearchInputListner?.unsubscribe();
        this.searchTermListener?.unsubscribe();
        this.setNDCSpecificListener?.unsubscribe();
        this.getCategoriesSubscription?.unsubscribe();
    }

}
