<template>
	<section class="home-page">
		<div class="home-page__header">
			<!-- Display just "Welcome" when user is signed out -->
			<VindiAvatar
				:size="80"
				:profile="$store.state.profile"
				:open-profile="false"
			/>
			<div class="home-page__welcome">
				<h2>
					{{ $t('HOMEPAGE_WELCOME') }}
				</h2>
				<h1>
					{{ firstName }}
				</h1>
			</div>
		</div>
		
		<Container class="home-page__content">
			<div class="home-page__overview">
				<div
					v-if="invited.length > 0"
					class="home-page__invited"
					role="button"
					tabindex="0"
					@click="invitesDialog = true"
				>
					<w-icon size="1.5rem">
						mdi mdi-star
					</w-icon>
					<div>
						<div class="home-page__invited-title">
							You have {{ invited.length }} pending project invitations
						</div>
						<div class="home-page__invited-subtitle">
							Click to view your invitations
						</div>
					</div>
				</div>

				<HomeStarredView
					v-if="starred.length > 0"
					:starred="starred"
				/>

				<HomeProjectsView
					:projects="projects"
					@create="openProjectCreation"
				/>
				
				<HomeTeamsView
					v-if="teams.length"
					:teams="teams"
				/>
			</div>
			<aside class="home-page__sidebar">
				<HomeActivity />
				<HomeFocus />
			</aside>
		</Container>

		<w-dialog
			v-model="invitesDialog"
			dialog-class="simple-dialog simple-dialog--flat project-invites-dialog"
			width="600"
		>
			<div class="simple-dialog__content">
				<VindiTitle icon="mdi mdi-star">
					Accept invitations
				</VindiTitle>
			
				<p>
					You have been invited to participate in one or more projects.
					Select the invitations you would like to accept.
				</p>
			</div>

			<w-table
				class="project-invites-dialog__table"
				:headers="inviteTableHeaders"
				:items="invited"
			>
				<template #header-label="{ label, header }">
					<w-checkbox
						v-if="header.key == 'name'"
						:value="selectedInvites.length > 0"
						:indeterminate="invited.length != selectedInvites.length"
						class="project-invites-dialog__select-all"
						@click.native.stop
						@input="updateAllInvites"
					/>
					{{ label }}
				</template>
				
				<template #[`item-cell.name`]="{ item }">
					<w-checkbox
						v-model="item.selected"
					>
						<div class="project-invites-dialog__name">
							{{ item.name }}
							<div class="project-invites-dialog__slug">
								{{ item.slug }}
							</div>
						</div>
					</w-checkbox>
				</template>

				<template #[`item-cell.creatorName`]="{ item }">
					<VindiProfile :profile="item.creator" />
				</template>
			</w-table>

			<w-divider class="nm" />

			<div class="simple-dialog__content">
				<w-alert
					class="nmt"
					:value="showInviteAlert"
					error
				>
					{{ invited.length - selectedInvites.length }} invitations will be declined
				</w-alert>
				<w-flex>
					<w-button
						bg-color="shade-2"
						@click="invitesDialog = false"
					>
						Close
					</w-button>
					<VindiSpacer />
					<w-button
						color="white"
						bg-color="primary"
						:loading="invitesLoading"
						@click="acceptSelectedInvites"
					>
						Accept {{ selectedInvites.length || 'no' }} invitations
					</w-button>
				</w-flex>
			</div>
		</w-dialog>
	</section>
</template>

<script lang="ts">
import Vue from 'vue';
import { Optional } from '../typings/helpers';
import fetchProjects from '~/assets/query/home/fetchProjects.gql';
import fetchHomePage from '~/assets/query/home/fetchHomePage.gql';
import acceptInvites from '~/assets/query/home/acceptInvites.gql';

export default Vue.extend({

	async asyncData({ store, redirect, $api }) {
		if(!store.state.profile) {
			redirect('/explore');
			return;
		}

		const result = await $api.query(fetchHomePage);
		
		return {
			projects: result.access,
			starred: result.starred,
			teams: result.teams,
			invited: result.invited.map((project: any) => ({
				...project,
				creatorName: project.creator.fullName,
				selected: true
			}))
		};
	},

	data: () => ({
		invited: [] as any[],
		projects: [] as any[],
		starred: [] as any[],
		teams: [] as any[],
		invitesDialog: false,
		invitesLoading: false,
		inviteTableHeaders: [
			{ label: 'Project', key: 'name' },
			{ label: 'Owner', key: 'creatorName' }
		]
	}),

	computed: {
		firstName(): Optional<string> {
			return this.$store.state.profile?.firstName;
		},

		selectedInvites(): any[] {
			return this.invited.filter(project => project.selected);
		},

		showInviteAlert(): boolean {
			return this.selectedInvites.length < this.invited.length;
		}
	},

	mounted() {
		const verified = this.$route.query.verified;
		const action = this.$route.query.action;

		if(verified !== undefined) {
			if(verified == 'true') {
				this.$waveui.notify({
					message: 'Verification successful',
					success: true,
				});
			} else if(verified == 'false') {
				this.$waveui.notify({
					message: 'Verification failed. Please check your email for a new link.',
					error: true,
				});
			}

			this.$router.push("/");
		}

		if(action == 'show_invitations' && this.invited.length) {
			this.invitesDialog = true;
		}
	},

	methods: {
		openProjectCreation() {
			this.$store.commit('viewNewProjectDialog', true);
		},
		
		updateAllInvites(value: boolean) {
			this.invited.forEach(invited => {
				invited.selected = value;
			});
		},

		async acceptSelectedInvites() {
			this.invitesLoading = true;

			await this.$api.query(acceptInvites, {
				projects: this.selectedInvites.map(project => project.id)
			});

			const res = await this.$api.query(fetchProjects);

			this.invitesDialog = false;
			this.projects = res.projects;

			setTimeout(() => {
				this.invited = [];
			}, 500);
		}
	}
});
</script>

<style lang="scss">
.home-page {

	&__header {
		height: $header-height;
		margin-top: -$toolbar-height;
		background-color: var(--color-shade-0);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	&__welcome {
		@include padding(6, l);
		@include font-weight(semibold);
		@include font-size('2xl');
	}

	&__content {
		display: grid;
		grid-template-columns: repeat(7, minmax(0, 1fr));
		
		@include breakpoint(lg) {
			gap: 4rem;
		}
	}

	&__overview {
		@include padding(8, y);

		grid-column: 1 / -1;

		@include breakpoint(md) {
			grid-column: span 4 / span 4;
		}

		@include breakpoint(lg) {
			grid-column: span 5 / span 5;
		}
	}

	&__sidebar {
		@include margin(-20, t);

		order: -9999;
		grid-column: 1 / -1;
		display: flex;
		flex-direction: column;
		gap: 2.5rem;

		@include breakpoint(md) {
			grid-column: span 3 / span 3;
			order: 0;
		}

		@include breakpoint(lg) {
			grid-column: span 2 / span 2;
		}
	}

	&__invited {
		@include shadow;
		@include padding(4, x);
		@include padding(3, y);
		@include margin(8, b);
		@include rounded(lg);

		background-color: var(--color-info);
		align-items: center;
		cursor: pointer;
		display: flex;
		color: white;
		gap: 0.85rem;
	}

	&__invited-title {
		@include font-weight(medium);
	}

	&__invited-subtitle {
		@include font-size(sm);

		opacity: 0.8;
	}
}

.project-invites-dialog {

	&__table {
		min-height: 18rem;
	}

	&__select-all {
		@include margin(5, r);
	}

	&__name {
		@include margin(2, l);
	}

	&__slug {
		@include font-size(sm);

		opacity: 0.5;
	}

	&__decline {
		@include margin(1, t);
		@include font-size(sm);

		color: gray;
	}

	p {
		@include margin(5, t);

		color: #808080;
	}
}
</style>