<template>
	<section class="project-page">
		<ProjectSidebar
			v-model="viewIndicator"
			:project="project"
			:get-path="getPath"
		/>

		<section class="project-page__wrapper">
			<AppToolbar class="project-page__toolbar">
				<w-menu
					custom
					align-left
					hide-on-menu-click
					transition="slide-fade-down"
				>
					<template #activator="{ on }">
						<w-button
							class="project-page__options"
							icon="mdi mdi-chevron-down"
							bg-color="transparent"
							xl
							v-on="on"
						/>
					</template>
					<div class="simple-list">
						<p class="simple-list__title">
							{{ $t('PROJECT_OPTIONS') }}
						</p>
						<w-divider />
						<div class="simple-list__list">
							<template v-if="project.accessLevel == 'manager'">
								<router-link
									:to="getPath('settings')"
									class="simple-list__item project-page__settings-item"
									tag="div"
								>
									<w-icon size="1.1rem" class="left">
										mdi mdi-cog-outline
									</w-icon>
									<div>
										<div>
											Settings
										</div>
										<small>
											Project management
										</small>
									</div>
								</router-link>
								<w-divider />
							</template>
							<div
								class="simple-list__item"
								@click="promptManageLabels"
							>
								<w-icon size="1.1rem">
									mdi mdi-tag-text
								</w-icon>
								Task labels
							</div>
							<div class="simple-list__item">
								<w-icon size="1.1rem">
									mdi mdi-lightning-bolt
								</w-icon>
								Automation rules
							</div>
							<div class="simple-list__item">
								<w-icon size="1.1rem">
									mdi mdi-bell
								</w-icon>
								Notifications
							</div>
							<div class="simple-list__item">
								<w-icon size="1.1rem">
									mdi mdi-archive
								</w-icon>
								Archived items
							</div>

							<div v-if="project.accessLevel == 'manager'">
								<w-divider />

								<div class="member-list">
									<div class="member-list__header">
										Members
										<VindiSpacer />
										<router-link :to="getPath('settings/members')">
											<small class="member-list__edit">
												Manage
											</small>
										</router-link>
									</div>
									<div class="member-list__entries">
										<VindiAvatar
											v-for="{ member } in project.members"
											:key="member.id"
											class="-mr-2 block"
											:profile="member"
											:size="30"
										/>
									</div>
								</div>

								<div v-if="project.teams.length > 0" class="member-list">
									<div class="member-list__header">
										Teams
										<VindiSpacer />
										<router-link :to="getPath('settings/teams')">
											<small class="member-list__edit">
												Manage
											</small>
										</router-link>
									</div>
									<div class="member-list__entries">
										<team-icon
											v-for="{ team } in project.teams"
											:key="team.id"
											class="mr-1 block"
											:team="team"
											:size="30"
										/>
									</div>
								</div>
							</div>
						</div>

						<div v-if="project.accessLevel != 'manager'">
							<w-divider style="margin: 0; margin-bottom: 2px;" />

							<div
								class="simple-list__item error"
								@click="leaveProject"
							>
								<w-icon size="1.1rem">
									mdi mdi-logout
								</w-icon>
								{{ $t('PROJECT_LEAVE') }}
							</div>
						</div>
					</div>
				</w-menu>

				<div class="project-page__info">
					<h1 class="project-page__name">
						{{ project.name }}

						<w-icon
							class="project-page__star"
							:class="starClass"
							@click="toggleStar"
						>
							mdi mdi-star
						</w-icon>
					</h1>
					<small
						v-if="view"
						class="project-page__view"
					>
						{{ $t(view.name) }}
					</small>
				</div>

				<template #creation-list>
					<div
						class="simple-list__item"
					>
						<w-icon size="1.1rem">
							mdi mdi-text-box-check
						</w-icon>
						{{ $t('TOOLBAR_CREATE_TASK') }}
						<p class="text-gray-400">
							{{ $t('TOOLBAR_CREATE_TASK_DESC') }}
						</p>
					</div>
				</template>
			</AppToolbar>

			<main role="main" class="project-page__content">
				<keep-alive>
					<NuxtChild
						:project="project"
					/>
				</keep-alive>
			</main>

			<ProjectCreationDialogs
				:project="project"
			/>
		</section>
	</section>
</template>

<script lang="ts">
import Vue from "vue";
import fetchProjectPage from '~/assets/query/project/fetchProjectPage.gql';
import favoriteProject from '~/assets/query/project/favoriteProject.gql';
import onLabelsChanged from '~/assets/query/project/onLabelsChanged.gql';
import leaveProject from '~/assets/query/project/leaveProject.gql';
import { parseSlug } from '~/src/helpers';
import { ProjectView } from "~/registry/projectViews";
import { Optional } from "~/typings/helpers";
import { CreationProvider } from "~/typings/models";

export default Vue.extend({
	layout: 'empty',

	async asyncData(context) {
		const pid = parseSlug(context.params.pid);

		// Assert project existence
		if(pid == undefined) {
			context.error({
				statusCode: 404,
				message: 'Project not found'
			});
			return;
		}

		// TODO Fetch the task lists on the fly or
		// keep the lists up to date w/ subscriptions
		const res = await context.$api.query(fetchProjectPage, {
			pid: pid
		});

		const project = res.project;

		if(!project) {
			context.error({
				statusCode: 404,
				message: 'Project not found'
			});
			return;
		}
		
		// Initial view indicator position
		const views = context.$registries.projectViews;
		const segments = context.route.matched[1].path.split('/');
		const viewInstance = views.get(segments[segments.length - 1]);
		const indicator = viewInstance ? views.toArray().indexOf(viewInstance) : -1;

		return {
			view: viewInstance,
			viewIndicator: indicator,
			project: project
		};
	},

	data: () => ({
		view: null as unknown as Optional<ProjectView>,
		manager: null as any,
		project: {} as any,
		viewIndicator: 0
	}),

	computed: {
		starClass(): any {
			return {
				'project-page__star--active': this.project.isStarred
			};
		}
	},

	watch: {
		'$route'() {
			this.updateIndicator();
		}
	},

	mounted() {
		this.manager = this.$api.createManager();

		// Update project labels
		this.manager.subscribe({
			query: onLabelsChanged,
			variables: {
				id: this.project.id
			},
			next: (result: any) => {
				this.project.labels = result.labelsChanged.labels;
			}
		});

		this.$store.commit('addCreationProvider', {
			id: 'task',
			order: 20,
			icon: 'mdi mdi-text-box',
			title: 'TOOLBAR_CREATE_TASK',
			description: 'TOOLBAR_CREATE_TASK_DESC',
			handler: () => this.promptNewTask()
		} as CreationProvider);
	},

	beforeDestroy() {
		this.$store.commit('removeCreationProvider', 'task');
		this.manager.dispose();
	},

	methods: {

		getPath(path?: string): string {
			return `/project/${this.$route.params.pid}/${path || ''}`;
		},

		updateIndicator() {
			const views = this.$registries.projectViews;
			const segments = this.$route.matched[1].path.split('/');
			const viewInstance = views.get(segments[segments.length - 1]);

			this.view = viewInstance;

			if(!viewInstance) {
				this.viewIndicator = -1;
			} else {
				this.viewIndicator = views.toArray().indexOf(viewInstance);
			}
		},

		promptNewTask() {
			this.$store.commit('viewNewTaskDialog', true);
		},

		promptManageLabels() {
			this.$store.commit('viewLabelManageDialog', true);
		},

		async leaveProject() {
			const success = await this.$api.query(leaveProject, {
				id: this.project.id
			});

			if(success) {
				this.$waveui.notify({
					message: `Successfully left project ${this.project.name}`,
					success: true
				});

				this.$router.push("/");
			} else {
				this.$waveui.notify({
					message: `Failed to leave project ${this.project.name}`,
					error: true
				});
			}
		},

		toggleStar() {
			this.project.isStarred = !this.project.isStarred;

			if(this.project.isStarred) {
				this.$waveui.notify({
					message: `Favorited ${this.project.name}`,
					icon: 'mdi mdi-star',
					color: 'amber'
				});
			}

			this.$api.query(favoriteProject, {
				projectId: this.project.id
			});
		}
	}
});
</script>

<style lang="scss">
.project-page {
	display: flex;
	min-height: 100vh;

	&__wrapper {
		display: flex;
		flex-direction: column;
		flex-grow: 1;
		min-width: 0;
	}

	&__star {
		@include transition(opacity);
		@include transition(colors);
		@include margin(1, l);

		color: var(--color-shade-4);
		font-size: 1.1rem;
		opacity: 0.7;
		cursor: pointer;

		&:hover, &--active {
			opacity: 1;
		}

		&--active {
			color: #f7a715;
		}
	}

	&__settings-item {
		display: flex;
		align-items: center;
		line-height: 1rem;
	}

	&__options {
		@include margin(3, x);

		color: #404040;

		@include dark {
			color: #c5c5c5;
		}
	}

	&__info {
		display: flex;
		flex-direction: column;
	}

	&__name {
		@include font-weight(bold);
	}

	&__view {
		@include font-weight(thin);
		@include margin(-1, t);
	}

	&__content {
		flex-grow: 1;
	}
}

.project-view-empty {
	@include padding(40, y);

	display: flex;
	align-items: center;
	flex-direction: column;

	h2 {
		@include font-size('2xl');
		@include font-weight(medium);
		@include margin(8, t);

		color: #525252;

		@include dark {
			color: white;
		}
	}

	p {
		@include font-size(lg);
		@include margin(3, t);

		color: #a3a3a3;
		text-align: center;
		max-width: 400px;
	}

	.w-button {
		@include margin(6, t);
	}
}

.member-list {
	&__header {
		@include padding(3, x);
		@include padding(1, b);
		@include margin(2, t);
		@include font-weight(semibold);

		color: #35353a;
		display: flex;
		align-items: center;

		@include dark {
			color: #e5e5e5;
		}
	}

	&__edit {
		@include font-weight(medium);

		text-decoration: underline;
		cursor: pointer;
		color: #737373;
	}

	&__entries {
		@include padding(3, x);
		@include padding(2, b);

		display: flex;
		flex-wrap: wrap;
	}
}
</style>