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

		<spacer />

		<!-- ANCHOR Search bar -->
		<w-menu
			:value="isSearching && search.length"
			content-class="toolbar__search-panel"
			min-width="24rem"
		>
			<template #activator="{ on }">
				<div class="toolbar__search">
					<w-input
						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"
						v-on="on"
						@focus="isSearching = true"
						@blur="isSearching = false"
					/>
				</div>
			</template>
			<div v-if="search.length < 3">
				{{ $t("TOOLBAR_SEARCH_LENGTH") }}
			</div>
			<div v-else-if="searchResults.total == 0">
				{{ $t("TOOLBAR_SEARCH_NO_RESULTS") }}
			</div>
			<div v-else-if="!searchResults.present">
				{{ $t("TOOLBAR_SEARCH_SEARCHING") }}
			</div>
			<template v-else>
				<div v-if="searchResults.users.length > 0">
					<section-title icon="mdi mdi-folder-open">
						{{ $t("GENERAL_USERS") }}
					</section-title>
					<router-link
						v-for="(user, index) in searchResults.users"
						:key="index"
						:to="`/profile/${user.id}`"
						class="flex items-center mt-3"
					>
						<profile-bit :profile="user" />
					</router-link>
				</div>
				<div v-if="searchResults.teams.length > 0">
					<section-title icon="mdi mdi-folder-open">
						{{ $t("GENERAL_TEAMS") }}
					</section-title>
					<router-link
						v-for="(team, index) in searchResults.teams"
						:key="index"
						:to="`/team/${team.id}`"
						class="flex items-center mt-3"
					>
						{{ team.name }}
					</router-link>
				</div>
				<div v-if="searchResults.projects.length > 0">
					<section-title icon="mdi mdi-folder-open">
						{{ $t("GENERAL_PROJECTS") }}
					</section-title>
					<router-link
						v-for="(project, index) in searchResults.projects"
						:key="index"
						:to="`/project/${project.id}`"
						class="flex items-center mt-3"
					>
						{{ project.name }}
					</router-link>
				</div>
			</template>
		</w-menu>

		<template v-if="$store.state.profile">
			<!-- ANCHOR Create new button -->
			<w-menu
				hide-on-menu-click
				align-center
				custom
			>
				<template #activator="{ on }">
					<w-button
						icon="mdi mdi-plus-circle"
						color="accent-1"
						to="#"
						xl
						v-on="on"
					/>
				</template>
				<div class="list-menu">
					<p class="list-menu__title">
						{{ $t("TOOLBAR_CREATE") }}
					</p>
					<w-divider />
					<div class="list-menu__list">
						<template v-for="(item, i) in creationItems">
							<div
								:key="`item${i}`"
								class="list-menu__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>

			<!-- Notification button -->
			<w-button
				color="misc-0"
				icon="mdi mdi-bell"
				xl
			/>

			<!-- 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"
				align-right
				custom
			>
				<template #activator="{ on }">
					<div
						class="toolbar__account"
						v-on="on"
					>
						<h1 class="toolbar__account-name">
							{{ userName }}
						</h1>
						<avatar
							class="toolbar__account-avatar"
							:profile="$store.state.profile"
							:open-profile="false"
						/>
					</div>
				</template>
				<div class="list-menu">
					<p class="list-menu__title">
						{{ $t("YOUR_ACCOUNT") }}
					</p>
					<w-divider />
					<div class="list-menu__list">
						<router-link
							:to="$store.state.profile.profileUrl"
							class="list-menu__item"
							tag="div"
						>
							<w-icon size="1.1rem">
								mdi mdi-account
							</w-icon>
							{{ $t("YOUR_ACCOUNT_PROFILE") }}
						</router-link>
						<router-link
							to=""
							class="list-menu__item"
							tag="div"
						>
							<w-icon size="1.1rem">
								mdi mdi-animation
							</w-icon>
							{{ $t("YOUR_ACCOUNT_PROJECTS") }}
						</router-link>
						<router-link
							to=""
							class="list-menu__item"
							tag="div"
						>
							<w-icon size="1.1rem">
								mdi mdi-briefcase
							</w-icon>
							{{ $t("YOUR_ACCOUNT_TEAMS") }}
						</router-link>
						<router-link
							to=""
							class="list-menu__item"
							tag="div"
						>
							<w-icon size="1.1rem">
								mdi mdi-google-analytics
							</w-icon>
							{{ $t("YOUR_ACCOUNT_ACTIVITY") }}
						</router-link>
						<w-divider />
						<router-link
							v-show="admin"
							to="/admin"
							class="list-menu__item"
							tag="div"
						>
							<w-icon size="1.1rem">
								mdi mdi-gavel
							</w-icon>
							{{ $t("YOUR_ACCOUNT_ADMIN") }}
						</router-link>
						<router-link
							to="/settings"
							class="list-menu__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="list-menu__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="list-menu__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="accent-2"
								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="list-menu__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>
		</template>
		<div v-else>
			<w-button
				bg-color="accent-1"
				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>

		<!-- ANCHOR Project creation dialog -->
		<w-dialog
			v-model="newProjectDialog"
			dialog-class="simple-dialog"
			width="600"
		>
			<section-title icon="mdi mdi-folder-multiple-plus">
				{{ $t("CREATE_NEW_PROJECT") }}
			</section-title>

			<label v-html="$t('CREATE_NEW_PROJECT_NAME')" />
			<w-input
				v-model="newProjectName"
			/>

			<label v-html="$t('CREATE_NEW_DESC')" />
			<w-textarea
				v-model="newProjectDesc"
				rows="3"
			/>

			<label v-html="$t('CREATE_NEW_INVITE_MEMBERS')" />

			<div class="addition-list">
				<!-- TODO Implement member addition -->
				<Avatar
					v-for="i in tempMemberCount"
					:key="i"
					:profile="$store.state.profile"
					:open-profile="false"
					:size="44"
				/>
				<div
					v-if="tempMemberCount < 12"
					class="addition-list__add-btn"
					@click="tempMemberCount++"
				>
					<w-icon>
						mdi mdi-plus
					</w-icon>
				</div>
			</div>

			<div class="simple-dialog__options">
				<spacer />
				<w-button
					color="white"
					bg-color="accent-2"
					:loading="newProjectLoading"
					:disabled="!newProjectName"
					@click="createProject"
				>
					<w-icon class="left">
						mdi mdi-plus
					</w-icon>
					{{ $t("CREATE_NEW_PROJECT_CREATE") }}
				</w-button>
			</div>
		</w-dialog>

		<!-- ANCHOR Team creation dialog -->
		<w-dialog
			v-model="newTeamDialog"
			dialog-class="simple-dialog"
			width="600"
		>
			<section-title icon="mdi mdi-account-multiple-plus">
				{{ $t("CREATE_NEW_TEAM") }}
			</section-title>

			<label v-html="$t('CREATE_NEW_TEAM_NAME')" />
			<w-input
				v-model="newTeamName"
			/>

			<label v-html="$t('CREATE_NEW_DESC')" />
			<w-textarea
				v-model="newTeamDesc"
				rows="3"
			/>

			<label v-html="$t('CREATE_NEW_INVITE_MEMBERS')" />

			<div class="addition-list">
				<!-- TODO Implement member addition -->
				<Avatar
					v-for="i in tempMemberCount"
					:key="i"
					:profile="$store.state.profile"
					:open-profile="false"
					:size="44"
				/>
				<div
					v-if="tempMemberCount < 12"
					class="addition-list__add-btn"
					@click="tempMemberCount++"
				>
					<w-icon>
						mdi mdi-plus
					</w-icon>
				</div>
			</div>

			<div class="simple-dialog__options">
				<spacer />
				<w-button
					color="white"
					bg-color="accent-2"
					:loading="newTeamLoading"
					:disabled="!newTeamName"
					@click="createTeam"
				>
					<w-icon class="left">
						mdi mdi-plus
					</w-icon>
					{{ $t("CREATE_NEW_TEAM_CREATE") }}
				</w-button>
			</div>
		</w-dialog>
	</header>
</template>

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

interface SearchInterface {
	projects: object[];
	teams: object[];
	users: object[];
}

export default Vue.extend({
	name: "Toolbar",

	data: () => ({
		executeSearchDebounced: null as unknown as Function,
		isScrolling: false,

		// Project creation
		newProjectDialog: false,
		newProjectName: "",
		newProjectDesc: "",
		newProjectLoading: false,
		tempMemberCount: 1,

		// Team creation
		newTeamDialog: false,
		newTeamName: "",
		newTeamDesc: "",
		newTeamLoading: false,

		// Search field
		isSearching: false,
		search: "" as string,
		searchResults: {} as SearchInterface | {}
	}),

	computed: {
		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,
			};
		},
		creationItems(): any {
			const items: any[] = [
				{
					icon: "mdi mdi-folder-open",
					title: "TOOLBAR_CREATE_PROJECT",
					description: "TOOLBAR_CREATE_PROJECT_DESC",
					handler: this.openProjectCreation,
				},
				{
					icon: "mdi mdi-account-group",
					title: "TOOLBAR_CREATE_TEAM",
					description: "TOOLBAR_CREATE_TEAM_DESC",
					handler: this.openTeamCreation,
				},
			];

			// for (const matched of this.$route.matched) {
			// 	const creation = matched.meta.creation as ToolbarCreationItem[];

			// 	if (creation) {
			// 		const entries = creation.map((item) => {
			// 			return { ...item, handler: () => {
			// 				const component = matched.instances.default as any;

			// 				if (typeof item.handler == "string") {
			// 					(component[item.handler] as Function)?.bind(component)?.();
			// 				} else {
			// 					item.handler();
			// 				}
			// 			} };
			// 		});

			// 		if (entries.length > 0) {
			// 			items.push(...entries);
			// 		}
			// 	}
			// }

			return items;
		},
	},

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

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

			this.executeSearchDebounced();
		}
	},

	mounted() {
		this.executeSearchDebounced = debounce(this.executeSearch, 500);
		this.checkIsFloating();

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

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

	methods: {
		getScrollView() {
			return this.$el.parentElement;
		},

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

		openProjectCreation() {
			this.newProjectDialog = true;
			this.newProjectName = "";
			this.newProjectDesc = "";
		},

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

		async createProject() {
			this.newProjectLoading = true;

			const res = await this.$api.query(createProject, {
				data: {
					name: this.newProjectName,
					description: this.newProjectDesc,
					public: false,
				},
			});

			this.newProjectLoading = false;
			this.newProjectDialog = false;

			this.$router.push(res.createProject.projectUrl);
			this.$waveui.notify({
				message: this.$t("NOTIFICATION_CREATE_PROJECT", [
					this.newProjectName,
				]),
				success: true,
			});
		},

		openTeamCreation() {
			this.newTeamDialog = true;
			this.newTeamName = "";
			this.newTeamDesc = "";
		},

		async createTeam() {
			this.newTeamLoading = true;

			const res = await this.$api.query(createTeam, {
				data: {
					name: this.newTeamName,
					description: this.newTeamDesc,
				},
			});

			this.newTeamLoading = false;
			this.newTeamDialog = false;

			this.$router.push(res.createTeam.teamUrl);
			this.$waveui.notify({
				message: this.$t("NOTIFICATION_CREATE_TEAM", [
					this.newTeamName,
				]),
				success: true,
			});
		},

		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);

			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;
	top: 0;
	z-index: 10;

	&__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: 24rem;
		opacity: 0.8;
		margin: 0 auto;

		&:hover {
			opacity: 1;
		}

		input {
			color: #262626;

			&::placeholder {
				color: #737373;
			}
		}

		.w-card {
			@include rounded(md);

			left: 0 !important;
			top: 28px !important;
			background-color: white;
		}
	}

	&__search-panel {
		@include rounded(lg);

		border: 1px solid var(--color-shade-3);
		background-color: var(--color-shade-1);
	}

	&__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;
	}

	&__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 {
		box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 20px 25px -5px, rgba(0, 0, 0, 0.04) 0px 10px 10px -5px;
	}

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

.addition-list {
	display: flex;

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

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

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

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

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