<template>
	<w-menu
		v-model="iconMenu"
		z-index="600"
		class="icon-picker"
		align-left
		bottom
		custom
	>
		<template #activator>
			<w-input
				v-model="searchFilter"
				:inner-icon-left="localValue || 'mdi mdi-chevron-down'"
				class="icon-picker__input"
				inner-icon-right="mdi mdi-close"
				placeholder="Search an icon..."
				autocomplete="off"
				@focus="openMenu"
				@click:inner-icon-right="clear"
			/>
		</template>
		<div class="icon-picker__list">
			<div
				v-if="iconList.length"
				class="icon-picker__list-inner"
			>
				<w-button
					v-for="icon in iconList"
					:key="icon"
					:icon="formatIcon(icon)"
					color="misc-0"
					lg
					@click="selectIcon(icon)"
				/>
			</div>
			<div
				v-else
				class="icon-picker__status"
			>
				{{ isLoading ? 'Loading...' : 'No results found' }}
			</div>
		</div>
	</w-menu>
</template>

<script lang="ts">
import gql from 'graphql-tag';
import { debounce } from 'lodash';
import Vue from 'vue';

export default Vue.extend({
	name: 'IconPicker',

	props: {
		value: {
			type: String
		}
	},

	data: () => ({
		iconList: [] as string[],
		localValue: '',
		searchFilter: '',
		isLoading: false,
		iconMenu: false,
		fetchDebounce: null as any
	}),

	watch: {
		value(value) {
			this.localValue = value;
		},
		searchFilter(value) {
			this.iconMenu = !!value;
			this.iconList = [];
			this.isLoading = true;
			this.fetchDebounce();
		}
	},

	created() {
		this.localValue = this.value || '';

		this.fetchDebounce = debounce(() => {
			this.fetchIcons();
		}, 500);
	},

	methods: {
		formatIcon(icon: string): string {
			return `mdi mdi-${icon}`;
		},

		openMenu() {
			if(this.searchFilter) {
				this.iconMenu = true;
			}
		},

		clear() {
			this.searchFilter = '';
			this.localValue = '';
			this.iconMenu = false;
		},

		async fetchIcons() {
			const res = await this.$api.query(gql`
				query ($search: String) {
					icons(query: $search)
				}
			`, {
				search: this.searchFilter
			});

			this.iconList = res.icons;
			this.isLoading = false;
		},

		selectIcon(icon: string) {
			const name = this.formatIcon(icon);

			this.localValue = name;
			this.$emit('input', name);
			this.iconMenu = false;
		}
	}
});
</script>

<style lang="scss">
.icon-picker {

	.w-input__icon--inner-right {
		@include font-size('2xl');

		top: 0;
		cursor: pointer;
	}

	&__list {
		@include glow(gray);
		@include rounded(xl);
		@include padding(4);

		max-height: 200px;
		background-color: var(--color-shade-0);
		overflow: hidden;
		overflow-y: auto;

		@include dark {
			@include glow(rgb(0, 0, 0));
			
			background-color: var(--color-shade-2);
		}
	}

	&__list-inner {
		display: grid;
		grid-template-columns: repeat(10, minmax(0, 1fr));
		gap: 0.75rem;
	}

	&__status {
		@include font-size(base);
		@include font-weight(medium);
	}
}


</style>