<template>
	<section v-if="user" class="admin-user">
		<VindiSaveBox
			v-model="user"
			:on-save="saveSettings"
		/>

		<div class="admin-user__profile">
			<VindiAvatar
				:size="80"
				:profile="user"
				:open-profile="false"
			/>
			<div class="admin-user__profile-info">
				<h2>
					{{ user.fullName }}
				</h2>
				<p>
					@{{ user.username }}
				</p>
			</div>
		</div>

		<Container class="admin-user__wrapper">
			<section class="admin-user__edit admin-user__sidebar-l">

				<!-- ANCHOR Flags -->
				<div class="admin-user__card">
					<div class="admin-user__card-title">
						Flags
					</div>

					<w-divider class="nm" />

					<div class="admin-user__card-content admin-user__flags">
						<w-flex>
							Account Enabled
							<VindiSpacer />
							<w-switch 
								v-model="user.isEnabled"
								:disabled="userIsViewer"
							/>
						</w-flex>
						<w-flex>
							Email Verified
							<VindiSpacer />
							<w-switch 
								v-model="user.isVerified"
							/>
						</w-flex>
						<w-flex>
							Authentic Badge
							<VindiSpacer />
							<w-switch 
								v-model="user.isAuthentic"
							/>
						</w-flex>
					</div>
				</div>
				
				<!-- ANCHOR Role -->
				<div class="admin-user__card">
					<div class="admin-user__card-title">
						Workspace Role
					</div>

					<w-divider class="nm" />

					<div class="admin-user__card-content">
						<w-select
							v-model="user.role"
							:items="allRoles"
							:disabled="userIsViewer"
						/>
					</div>
				</div>
			</section>

			<!-- ANCHOR Account information -->
			<section class="admin-user__card admin-user__center-content">
				<div class="admin-user__card-title">
					Account Information
				</div>

				<w-divider class="nm" />

				<w-form class="admin-user__card-content">
					<label>
						{{ $t('GENERAL_FULL_NAME') }}
					</label>
											
					<w-input
						v-model="user.fullName"
					/>

					<label>
						{{ $t('GENERAL_EMAIL') }}
					</label>
					<w-input
						v-model="user.email"
					/>
					
					<label>
						{{ $t('GENERAL_USERNAME') }}
					</label>
					<w-input
						v-model="user.username"
					/>

					<label v-html="$t('SETTINGS_PROFILE_BIO')" />
					<w-textarea
						v-model="user.bio"
						:placeholder="$t('SETTINGS_PROFILE_BIO_PLACEHOLDER')"
					/>

					<label v-html="$t('SETTINGS_PROFILE_LOCATION')" />
					<w-input
						v-model="user.location"
						:placeholder="$t('SETTINGS_PROFILE_LOCATION_PLACEHOLDER')"
					/>
							
					<label v-html="$t('SETTINGS_PROFILE_WEBSITE')" />
					<w-input
						v-model="user.website"
						:placeholder="$t('SETTINGS_PROFILE_WEBSITE_PLACEHOLDER')"
					/>
				</w-form>
			</section>

			<section class="admin-user__sidebar-r">

				<!-- ANCHOR Overview -->
				<div class="admin-user__card">
					<div class="admin-user__card-title">
						Overview
					</div>

					<w-divider class="nm" />

					<div class="admin-user__card-content admin-user__overview">
						<div>
							<w-icon class="pr-2" color="misc-1">
								mdi mdi-calendar-month
							</w-icon>
							{{ $t('PROFILE_JOINED', [ joinDate ]) }}
						</div>
						<div>
							<w-icon class="pr-2" color="misc-1">
								mdi mdi-eye
							</w-icon>
							{{ $t('PROFILE_LAST_ACTIVE', [ lastActiveDate ]) }}
						</div>
						<div>
							<w-icon class="pr-2" color="misc-1">
								mdi mdi-translate
							</w-icon>
							{{ $t('PROFILE_LANGUAGE', [ user.language ]) }}
						</div>
					</div>

					<w-divider class="nm" />


					<div class="admin-user__card-content admin-user__actions">
						<w-menu
							transition="slide-fade-down"
							hide-on-menu-click
							custom
						>
							<template #activator="{ on }">
								<w-button text v-on="on">
									Account Actions
									<w-icon class="right">
										mdi mdi-chevron-down
									</w-icon>
								</w-button>
							</template>
							<div class="simple-list admin-user__actions-list">
								<w-button
									text
									color="info"
									:disabled="passwordUpdateActive"
									@click="passwordDialog = true"
								>
									<w-icon size="1.1rem" class="left">
										mdi mdi-lock
									</w-icon>
									Change password
								</w-button>
								<w-button
									text
									color="error"
									:disabled="userIsViewer || deletionActive"
									@click="deletionDialog = true"
								>
									<w-icon size="1.1rem" class="left">
										mdi mdi-delete
									</w-icon>
									Delete user
								</w-button>
							</div>
						</w-menu>
					</div>
				</div>

				<!-- ANCHOR Comments -->
				<div class="admin-user__card">
					<div class="admin-user__card-title">
						Admin Comments
						<w-tooltip top>
							<template #activator="{ on }">
								<w-icon v-on="on">
									mdi mdi-information-outline
								</w-icon>
							</template>
							Private notes which are only viewable to other administrators.
						</w-tooltip>
					</div>
					
					<w-divider class="nm" />

					<div class="admin-user__card-content">
						<w-textarea
							v-model="user.adminNotes"
							rows="6"
						/>
					</div>
				</div>
			</section>
		</Container>

		<!-- ANCHOR Deletion dialog -->
		<!-- NOTE Perhaps we want to think this through a bit more. Archive support may be possible-->
		<w-dialog
			v-model="deletionDialog"
			width="350"
		>
			<VindiTitle icon="mdi mdi-delete">
				Delete User
			</VindiTitle>

			<w-divider />

			<div>
				<p>
					Are you sure?
				</p>
				<small>
					You are about to permanently delete this user. This cannot be undone!
				</small>
			</div>
			<w-flex>
				<w-button
					text
					bg-color="shade-2"
					:disabled="deletionActive"
					@click="deletionDialog = false"
				>
					Close
				</w-button>

				<VindiSpacer />

				<w-button
					bg-color="error"
					text
					:loading="deletionActive"
					@click="deleteUser"
				>
					Confirm
				</w-button>
			</w-flex>
		</w-dialog>

		<!-- ANCHOR Deletion dialog -->
		<!-- NOTE Perhaps we want to think this through a bit more. Archive support may be possible-->
		<w-dialog
			v-model="passwordDialog"
			width="350"
		>
			<VindiTitle icon="mdi mdi-lock">
				Update User Password
			</VindiTitle>

			<w-divider />

			<p v-html="$t('GENERAL_PASSWORD')" />
			<w-input
				v-model="newPassword"
				:placeholder="$t('SETTINGS_PROFILE_PASSWORD_PLACEHOLDER')"
				password-reveal
				type="password"
				name="password"
			/>

			<p v-html="$t('GENERAL_PASSWORD_CONFIRM')" />
			<w-input
				v-model="confirmNewPassword"
				:placeholder="$t('SETTINGS_PROFILE_PASSWORD_CONFIRM')"
				password-reveal
				type="password"
				name="password"
			/>

			<w-flex>
				<w-button
					text
					bg-color="shade-2"
					:disabled="passwordUpdateActive"
					@click="passwordDialog = false"
				>
					Close
				</w-button>

				<VindiSpacer />

				<w-button
					bg-color="primary"
					text
					:loading="passwordUpdateActive"
					:disabled="!canSavePassword"
					@click="updatePassword"
				>
					Save
				</w-button>
			</w-flex>
		</w-dialog>
	</section>
	<section v-else>
		<!-- TODO Better unknown user text  -->
		UNKNOWN USER
	</section>
</template>

<script lang="ts">
import Vue from 'vue';
import dayjs from 'dayjs';
import { parseSlug } from "~/src/helpers";
import AdminFetchUser from '~/assets/query/admin/adminFetchUser.gql';
import AdminUpdateUser from '~/assets/query/admin/adminUpdateUser.gql';
import AdminDeleteUser from '~/assets/query/admin/adminDeleteUser.gql';

export default Vue.extend({
	name: 'AdminUsersPage',
	middleware: "admin",

	async asyncData(context) {
		const result = await context.$api.query(AdminFetchUser, {
			uid: parseSlug(context.params.uid)
		});

		return {
			user: result.profileById
		};
	},

	data: () => ({
		original: null as any,
		user: null as any,
		deletionDialog: false,
		deletionActive: false,
		passwordDialog: false,
		newPassword: '',
		confirmNewPassword: '',
		passwordUpdateActive: false,
		allRoles: [
			{ label: "Administrator", value: 'admin' },
			{ label: "Member", value: 'member' }, 
		]
	}),

	computed: {
		joinDate(): string {
			return dayjs(parseInt(this.user.createdAt)).format(this.$t("DATE_TIME_FORMAT") as string);
		},
		
		lastActiveDate(): string {
			return dayjs(parseInt(this.user.lastSeenAt)).format(this.$t("DATE_TIME_FORMAT") as string);
		},

		userIsViewer(): boolean {
			return this.$store.state.profile.id === this.user.id;
		},
		canSavePassword(): boolean {
			if(this.newPassword !== '' && this.confirmNewPassword !== '' && this.confirmNewPassword === this.newPassword) {
				return true;
			} else {
				return false;
			}
		},
		passwordPlaceholder(): string {
			var placeholder = '';
			
			if(this.user.password) {
				placeholder = this.$t('SETTINGS_PROFILE_PASSWORD_PLACEHOLDER_FILLED').toString();
			} else {
				placeholder = this.$t('SETTINGS_PROFILE_PASSWORD_PLACEHOLDER_EMPTY').toString();
			}

			return placeholder;
		}
	},
	
	methods: {
		revertSettings() {
			this.user = this.original;
		},

		async deleteUser() {
			this.deletionDialog = false;
			this.deletionActive = true;

			const success = await this.$api.query(AdminDeleteUser, {
				id: this.user.id
			});

			if(success) {
				this.$router.push("/admin/users");

				this.$waveui.notify({
					message: 'User deletion successful', 
					success: true,
				});
			} else {
				this.$waveui.notify({
					message: 'User deletion failed', 
					error: true,
				});
			}

			this.deletionActive = false;
		},

		async updatePassword() {
			if(!this.canSavePassword) {
				this.$waveui.notify({
					message: 'Password update failed', 
					error: true,
				});

				return;
			}

			this.passwordDialog = false;
			this.passwordUpdateActive = true;

			await this.$api.query(AdminUpdateUser, {
				id: this.user.id,
				data: {
					password: this.newPassword
				}
			});

			this.newPassword = '';
			this.passwordUpdateActive = false;

			this.$waveui.notify({
				message: 'Password successfully updated', 
				success: true,
			});
		},

		async saveSettings() {
			await this.$api.query(AdminUpdateUser, {
				id: this.user.id,
				data: {
					isAuthentic: this.user.isAuthentic,
					isVerified: this.user.isVerified,
					isEnabled: this.user.isEnabled,
					role: this.user.role,
					name: this.user.fullName,
					email: this.user.email,
					username: this.user.username,
					website: this.user.website,
					bio: this.user.bio,
					location: this.user.location,
					adminNotes: this.user.adminNotes
				}
			});

			this.$waveui.notify({
				message: this.$t('USER_SAVE_SUCCESS'),
				success: true
			});

			this.original = this.user;
		}
	}
});

</script>

<style lang="scss">
.admin-user {
	
	&__profile {
		height: $header-height-small;
		margin-top: -$toolbar-height;
		padding-top: 3rem;
		display: flex;
		min-width: 500px;
		align-items: center;
		justify-content: center;
		background-color: var(--color-shade-0);
	}

	&__profile-info {
		@include padding(6, l);
		
		h2 {
			@include font-size(xl);
			@include font-weight(semibold);
			@include dark {
				color: #f3f4f6;
			}
		}

		p {
			@include font-size(sm);

			color: gray;
		}
	}

	&__wrapper {
		gap: 2rem;
		display: grid;
		grid-template-columns: repeat(4, minmax(0, 1fr));
	}

	&__sidebar-l {
		grid-column: 1 / span 1;
	}

	&__center-content {
		grid-column: 2 / span 2;
	}

	&__sidebar-r {
		grid-column: 4 / span 1;
	}

	&__card {
		@include shadow;
		@include margin(5, t);
		@include padding(0);
		@include rounded('2xl');
			
		border-width: 1px;
		border-color: #e2e8f0;
		background-color: white;

		@include dark {
			border-color: var(--color-shade-2);
			background-color: var(--color-shade-2);
		}
	}

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

		text-align: center;
	}

	&__card-content,
	&__card-title {
		@include padding(3);
	}

	&__flags, &__overview {
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
	}

	&__actions .w-button,
	&__actions-list .w-button {
		width: 100%;
	}

	&__actions-list {
		@include padding(2);

		display: flex;
		flex-direction: column;
		gap: 0.25rem;

		.w-button {
			justify-content: flex-start;
		}
	}

	.w-form label:not(:first-child) {
		@include margin(4, t);
	}
}
</style>