<template>
	<header
		ref="toolbar"
		class="toolbar shade-0--bg"
		:class="toolbarClass"
	>
		<slot>
			<VindiLogo />
		</slot>

		<VindiSpacer />

		<!-- ANCHOR Search bar -->
		<w-menu
			:value="isSearching"
			menu-class="toolbar__search-wrapper simple-list"
			transition="slide-fade-down"
			persistent
		>
			<template #activator>
				<div class="toolbar__search">
					<w-input
						ref="search"
						v-model="search"
						class="toolbar__search-field"
						inner-icon-left="mdi mdi-magnify"
						:placeholder="$t('TOOLBAR_SEARCH')"
						bg-color="shade-3"
						autocomplete="off"
						color="#eee"
						name="search"
						@focus="isSearching = true"
						@blur="isSearching = false"
					/>
				</div>
			</template>

			<!-- Searching status -->
			<div v-if="isQuerying" class="toolbar__searching">
				<w-progress
					circle
					:size="15"
				/>
				Searching...
			</div>
			
			<!-- No results found -->
			<div v-else-if="!searchResults.total && search" class="toolbar__no-results">
				No results found!
			</div>

			<!-- Recent searches -->
			<div v-else-if="!searchResults.total" class="toolbar__recent-searches">
				<div class="simple-subtitle">
					Recent searches
				</div>

				<div
					v-if="!recentSearches.length"
					class="toolbar__no-searches"
				>
					No previous search queries
				</div>

				<ul>
					<li
						v-for="(recent, i) in recentSearches"
						:key="i"
						@click="selectRecent(recent)"
					>
						<w-icon>
							mdi mdi-magnify
						</w-icon>
						{{ recent }}
					</li>
				</ul>
			</div>

			<!-- Search results -->
			<div class="toolbar__search-results">
				<SearchProjects
					v-if="projectResults.length > 0"
					:results="projectResults"
				/>
				
				<SearchTasks
					v-if="taskResults.length > 0"
					:results="taskResults"
				/>
				
				<SearchUsers
					v-if="userResults.length > 0"
					:results="userResults"
				/>

				<SearchTeams
					v-if="teamResults.length > 0"
					:results="teamResults"
				/>
			</div>
		</w-menu>

		<!-- ANCHOR Create new button -->
		<w-menu
			v-if="$store.state.profile"
			hide-on-menu-click
			align-center
			custom
		>
			<template #activator="{ on }">
				<w-button
					icon="mdi mdi-plus-circle"
					color="primary"
					to="#"
					xl
					v-on="on"
				/>
			</template>
			<div class="simple-list toolbar__creation-list">
				<p class="simple-list__title">
					{{ $t("TOOLBAR_CREATE") }}
				</p>
				<w-divider />
				<div class="simple-list__list">
					<template v-for="(item, i) in creationItems">
						<div
							:key="`item${i}`"
							class="simple-list__item"
							@click="item.handler"
						>
							<w-icon size="1.1rem">
								{{ item.icon }}
							</w-icon>
							{{ $t(item.title) }}
							<p class="text-gray-400">
								{{ $t(item.description) }}
							</p>
						</div>
						<w-divider
							v-if="i < creationItems.length - 1"
							:key="`div${i}`"
						/>
					</template>
				</div>
			</div>
		</w-menu>

		<!-- ANCHOR Notifications button -->
		<w-menu
			v-if="$store.state.profile"
			hide-on-menu-click
			align-center
			custom
		>
			<template #activator="{ on }">
				<w-button
					icon="mdi mdi-bell"
					color="misc-0"
					to="#"
					xl
					v-on="on"
				/>
			</template>
			<div class="simple-list toolbar__creation-list">
				<p class="simple-list__title">
					{{ $t("TOOLBAR_NOTIFICATIONS") }}
				</p>
				<w-divider />
				<div class="simple-list__list" style="text-align: center; padding: 5px 0px;">
					No new notifications!
				</div>
			</div>
		</w-menu>

		<!-- Explorer button -->
		<w-button
			color="misc-0"
			icon="mdi mdi-compass"
			route="/explore"
			xl
		/>

		<div class="toolbar__divider shade-2--bg" />

		<!-- ANCHOR Account menu -->
		<w-menu
			v-if="$store.state.profile"
			transition="slide-fade-down"
			hide-on-menu-click
			align-right
			custom
		>
			<template #activator="{ on }">
				<div
					class="toolbar__account"
					v-on="on"
				>
					<h1 class="toolbar__account-name">
						{{ userName }}
					</h1>
					<VindiAvatar
						class="toolbar__account-avatar"
						:profile="$store.state.profile"
						:open-profile="false"
					/>
				</div>
			</template>
			<div class="simple-list">
				<p class="simple-list__title">
					{{ $t("YOUR_ACCOUNT") }}
				</p>
				<w-divider />
				<div class="simple-list__list">
					<template v-if="admin">
						<router-link
							to="/admin"
							class="simple-list__item toolbar__admin-link"
							tag="div"
						>
							<w-icon size="1.1rem">
								mdi mdi-tools
							</w-icon>
							<div>
								<div>
									{{ $t("YOUR_ACCOUNT_ADMIN") }}
								</div>
								<small>
									Workspace management
								</small>
							</div>
						</router-link>
						<w-divider />
					</template>
					<router-link
						:to="$store.state.profile.profileUrl"
						class="simple-list__item"
						tag="div"
					>
						<w-icon size="1.1rem">
							mdi mdi-account
						</w-icon>
						{{ $t("YOUR_ACCOUNT_PROFILE") }}
					</router-link>
					<router-link
						to=""
						class="simple-list__item"
						tag="div"
					>
						<w-icon size="1.1rem">
							mdi mdi-animation
						</w-icon>
						{{ $t("YOUR_ACCOUNT_PROJECTS") }}
					</router-link>
					<router-link
						to=""
						class="simple-list__item"
						tag="div"
					>
						<w-icon size="1.1rem">
							mdi mdi-briefcase
						</w-icon>
						{{ $t("YOUR_ACCOUNT_TEAMS") }}
					</router-link>
					<router-link
						to=""
						class="simple-list__item"
						tag="div"
					>
						<w-icon size="1.1rem">
							mdi mdi-google-analytics
						</w-icon>
						{{ $t("YOUR_ACCOUNT_ACTIVITY") }}
					</router-link>
					<w-divider />
					<router-link
						to="/settings/account"
						class="simple-list__item"
						tag="div"
					>
						<w-icon size="1.1rem">
							mdi mdi-cog-outline
						</w-icon>
						{{ $t("YOUR_ACCOUNT_SETTINGS") }}
					</router-link>
					<a
						href="https://github.com/StarlaneStudios/vindigo"
						class="simple-list__item block"
						target="_blank"
					>
						<w-icon size="1.1rem">
							mdi mdi-help-circle-outline
						</w-icon>
						{{ $t("YOUR_ACCOUNT_HELP") }}
						<w-icon
							size="0.8rem"
							class="translate-y-0.5"
						>
							mdi mdi-open-in-new
						</w-icon>
					</a>
					<w-divider />
					<div class="simple-list__item" @click="toggleTheme">
						<w-icon size="1.1rem">
							mdi {{ $store.state.isDark ? 'mdi-brightness-4' : 'mdi-brightness-7' }}
						</w-icon>
						{{ $t('YOUR_ACCOUNT_DARK_MODE') }}
						<w-switch
							:value="$store.state.isDark"
							color="primary"
							class="theme-toggle"
							thin
							readonly
						/>
						<div>
							<small v-if="$store.state.isDark">{{ $t('YOUR_ACCOUNT_USING_DARK_MODE') }}</small>
							<small v-else>{{ $t('YOUR_ACCOUNT_USING_LIGHT_MODE') }}</small>
						</div>
					</div>
					<w-divider />
					<div
						class="simple-list__item error"
						@click="$store.dispatch('signOut')"
					>
						<w-icon size="1.1rem">
							mdi mdi-logout
						</w-icon>
						{{ $t("YOUR_ACCOUNT_SIGN_OUT") }}
					</div>
				</div>
			</div>
		</w-menu>
		<div v-else>
			<w-button
				bg-color="primary"
				color="white"
				route="/authenticate"
				class="toolbar__signin"
			>
				<w-icon class="left">
					mdi mdi-key-variant
				</w-icon>
				Sign in
				<span>/</span>
				Sign up
			</w-button>
		</div>
	</header>
</template>

<script lang="ts">
import Vue from "vue";
import executeSearch from '~/assets/query/toolbar/executeSearch.gql';
import { debounce, sum, values } from "lodash";
import { Optional } from "~/typings/helpers";
import { focusInput } from "~/src/helpers";

interface SearchInterface {
	projects: any[];
	teams: any[];
	users: any[];
	tasks: any[];
}

export default Vue.extend({

	data: () => ({
		executeSearchDebounced: null as unknown as Function,
		searchResults: {} as Partial<SearchInterface>,
		recentSearches: [] as string[],
		isScrolling: false,
		isSearching: false,
		isQuerying: false,
		search: '' as string
	}),

	computed: {
		creationItems(): any[] {
			return [
				...this.$store.state.creationItems
			].sort((left: any, right: any) => {
				return left.order - right.order;
			});
		},

		userID(): Optional<Number> {
			return this.$store.state.profile?.id;
		},
		userName(): Optional<string> {
			return this.$store.state.profile?.fullName;
		},
		admin(): boolean {
			return this.$store.state.profile?.role == "admin";
		},
		toolbarClass(): any {
			return {
				'toolbar--floating': this.isScrolling,
			};
		},
		projectResults(): any[] {
			return this.searchResults?.projects ?? [];
		},
		teamResults(): any[] {
			return this.searchResults?.teams ?? [];
		},
		userResults(): any[] {
			return this.searchResults?.users ?? [];
		},
		taskResults(): any[] {
			return this.searchResults?.tasks ?? [];
		}
	},

	watch: {
		search() {
			this.searchResults = {};
			this.isQuerying = false;

			if (this.search.length < 3) {
				return;
			}

			this.isQuerying = true;
			this.executeSearchDebounced();
		},
		isSearching(value) {
			if(!value && this.search) {

				// Remove existing references
				while(this.recentSearches.indexOf(this.search) >= 0) {
					this.recentSearches.splice(this.recentSearches.indexOf(this.search), 1);
				}

				// Prepend new search query
				this.recentSearches.unshift(this.search);

				// Trim oldest entries
				while(this.recentSearches.length > 5) {
					this.recentSearches.pop();
				}

				localStorage.setItem('vindigo:searches', JSON.stringify(this.recentSearches));
			}
		}
	},

	mounted() {
		this.recentSearches = JSON.parse(localStorage.getItem('vindigo:searches') || '[]');
		this.executeSearchDebounced = debounce(this.executeSearch, 500);
		this.checkIsFloating();

		window.addEventListener('scroll', this.checkIsFloating);
	},

	beforeDestroy() {
		window.removeEventListener('scroll', this.checkIsFloating);
	},

	methods: {
		callHandler(handler: Function) {
			handler(this);
		},

		selectRecent(search: string) {
			this.search = search;

			focusInput(this.$refs.search as any);
		},

		toggleTheme() {
			this.$store.commit('setDarkMode', !this.$store.state.isDark);
		},

		checkIsFloating() {
			this.isScrolling = document.documentElement.scrollTop > 0;
		},

		async executeSearch() {
			const res = await this.$api.query(executeSearch, {
				query: this.search
			});

			const result = res.search;
			const vals = values(result).map((it) => it.length);
			const total = sum(vals);

			// <div
			// 	v-if="search.length < 3"
			// 	class="toolbar__search-warning"
			// >
			// 	{{ $t("TOOLBAR_SEARCH_LENGTH") }}
			// </div>
			// <div
			// 	v-if="searchResults.total == 0"
			// >
			// 	{{ $t("TOOLBAR_SEARCH_NO_RESULTS") }}
			// </div>
			// <div v-else-if="!searchResults.present">
			// 	{{ $t("TOOLBAR_SEARCH_SEARCHING") }}
			// </div>

			this.isQuerying = false;
			this.searchResults = {
				...result,
				present: true,
				total: total
			};
		},
	},
});
</script>

<style lang="scss">
.toolbar {
	@include transition(shadow);

	display: flex;
	align-items: center;
	height: 3.5rem;
	position: sticky;
	z-index: 10;
	top: 0;

	&__divider {
		@include margin(4, x);

		width: 2px;
		height: 2.5rem;
	}

	&__search {
		@include transition(opacity);

		position: absolute;
		left: 0;
		right: 0;
		top: 0.75rem;
		max-width: 26rem;
		opacity: 0.8;
		margin: 0 auto;
	}

	&__search-wrapper {
		@include rounded(xl);
		
		overflow: hidden;
		width: 26rem;

		.w-card__content {
			max-height: 30rem;
			overflow-y: auto;
		}

		.simple-subtitle {
			@include padding(1, b);
		}

		.w-divider {
			margin-top: 0;
		}
	}

	&__recent-searches .simple-subtitle {
		@include margin(2, b);
	}

	&__searching, &__no-results {
		height: 100px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: gray;
		gap: 0.75rem;
	}

	&__no-searches {
		@include font-size(sm);

		color: gray;
	}

	&__recent-searches {
		@include margin(2, t);

		li {
			@include padding(0.75, y);

			cursor: pointer;
		
			&:hover {
				background-color: var(--color-shade-1);
			}
		}
	}

	&__search-results {
		display: flex;
		flex-direction: column;
		gap: 1.75rem;
	}

	&__search-count {
		@include font-size(xs);
		@include rounded(full);
		@include padding(0.3, y);
		@include padding(1.6, x);
		@include margin(1, l);
		@include margin(-0.25, t);

		background-color: var(--color-shade-2);
	}

	&__account {
		@include margin(2, r);
		
		display: flex;
		align-items: center;
		color: #292929;
		cursor: pointer;
	}

	&__account-name {
		@include font-size(base);
		@include font-weight(semibold);

		margin-bottom: 0;
		pointer-events: none;

		@include dark {
			color: white;
		}
	}

	&__account-avatar {
		@include margin(2, l);
		
		pointer-events: none;
	}

	&__admin-link {
		display: flex;
		align-items: center;
		line-height: 1rem;
		
		.w-icon {
			@include margin(2, r);
		}
	}

	&__signin {
		@include margin(3, r);
		@include padding(3, l);

		span {
			@include padding(1, x);

			opacity: 0.5;
		}
	}

	&__auth-divider {
		@include padding(1, x);

		opacity: 0.5;
	}

	&--floating {
		@include shadow;
	}

	.o-drop__trigger {
		display: flex;
		align-items: center;
	}

	&__creation-subtitle {
		margin-top: 6px;
		margin-left: 14px;
		text-align: left;
		color: gray;
	}

	&__creation-list {
		max-width: 18rem;
	}

	.w-button {
		@include margin(2, l);
	}
}

.addition-list {
	display: flex;

	> *:not(:first-child) {
		@include margin(-2, l);
	}

	&__add-btn {
		@include ring(rgba(map-get($theme-general, 'primary'), 0.4), 4);
		@include rounded(full);

		width: 3rem;
		height: 3rem;
		display: flex;
		background-color: var(--color-primary);
		justify-content: center;
		align-items: center;
		color: white;
		cursor: pointer;
	}
}

.theme-toggle {
	@include padding(2, l);

	transform: translateY(-1px);
}
</style>