import { Component, h, Event, EventEmitter, Prop, State, Element } from '@stencil/core'

export type TagOptions = {
    tags: string[]
    historyItemIds: string[]
}

@Component({
    tag: 'gd-user-dashboard-bulk-tag-dialog',
    styleUrl: 'gd-user-dashboard-bulk-tag-dialog.scss',
    shadow: true,
})
export class GdUserDashboardBulkTagDialog {
    /**
     * the history items to tag
     */
    @Prop() historyItemIds: string[] = []

    /**
     * when to show the dialog
     */
    @Prop() show: boolean = false

    /**
     * event emitted when the dialog is closed
     */
    @Event() closed: EventEmitter<void>

    /**
     * event emitted to tag items
     */
    @Event() addTags: EventEmitter<TagOptions>

    /**
     * the tags to be added
     */
    @State() newTags: string[] = []

    @Element() el: HTMLElement

    handleClose() {
        // @ts-ignore
        this.el.shadowRoot.querySelector('bs-modal').closeDialog()
    }

    tagItems() {
        if (!this.newTags.length) {
            // can only tag items if the user inputted tags
            return
        }

        // trigger the event to add tags
        this.addTags.emit({
            tags: this.newTags,
            historyItemIds: this.historyItemIds,
        })

        // visually wait a bit before closing
        setTimeout(() => {
            this.newTags = []
            this.handleClose()
        }, 1000)
    }

    /**
     * renders the dialog
     */
    render() {
        return (
            <bs-modal show={this.show} onClose={() => this.closed.emit()}>
                <bs-modal-header modal-title={`<bs-icon size="20" class="mr-2" icon="fab fa-tags"></bs-icon> Add Tags`} />

                <bs-modal-body>
                    <gd-tag-input variant="pills" placeholder="Add tag..." onTagsChange={(e: any) => (this.newTags = e.detail)} />
                </bs-modal-body>

                <bs-modal-footer>
                    <bs-button variant="secondary" onClick={this.handleClose.bind(this)}>
                        Cancel
                    </bs-button>

                    <bs-button variant="primary" onClick={this.tagItems.bind(this)} disabled={!this.newTags?.length}>
                        Add Tags
                    </bs-button>
                </bs-modal-footer>
            </bs-modal>
        )
    }
}
