<template>
	<section class="admin-dashboard">
		<Container>
			<w-flex
				class="admin-dashboard__header"
				align-center
				:gap="3"
			>
				<w-icon :size="40">
					mdi mdi-tools
				</w-icon>
				<div>
					<div class="admin-dashboard__title">
						Admin Dashboard
					</div>
					<div class="admin-dashboard__subtitle">
						Manage your Vindigo workspace
					</div>
				</div>
			</w-flex>
			<section class="admin-dashboard__statistics">

				<!-- ANCHOR Requests -->
				<w-card class="admin-dashboard__card">
					<w-flex>
						<div class="admin-dashboard__card-name">
							API Requests (30m)
						</div>
						<VindiSpacer />
						<w-icon :size="24">
							mdi mdi-swap-vertical-bold
						</w-icon>
					</w-flex>

					<div
						v-if="systemStats.requestMean < 0"
						class="admin-dashboard__card-value"
					>
						Waiting...
					</div>
					<div
						v-else
						class="admin-dashboard__card-value"
					>
						{{ systemStats.requestMean }}<small>/min avarage</small>
					</div>
				</w-card>

				<!-- ANCHOR Memory -->
				<w-card class="admin-dashboard__card">
					<w-flex>
						<div class="admin-dashboard__card-name">
							Memory Usage
						</div>
						<VindiSpacer />
						<w-icon :size="24">
							mdi mdi-lightning-bolt
						</w-icon>
					</w-flex>
					
					<div class="admin-dashboard__card-value">
						{{ formatBytes(systemStats.memoryUsage) }}
					</div>
				</w-card>

				<!-- ANCHOR Storage -->
				<w-card class="admin-dashboard__card">
					<w-flex>
						<div class="admin-dashboard__card-name">
							Storage Usage
						</div>
						<VindiSpacer />
						<w-icon :size="24">
							mdi mdi-database
						</w-icon>
					</w-flex>

					<div class="admin-dashboard__card-value">
						{{ formatBytes(systemStats.storageUsage) }}
					</div>
				</w-card>

				<!-- ANCHOR Uptime -->
				<w-card class="admin-dashboard__card">
					<w-flex>
						<div class="admin-dashboard__card-name">
							Server Uptime
						</div>
						<VindiSpacer />
						<w-icon :size="24">
							mdi mdi-clock
						</w-icon>
					</w-flex>

					<div class="admin-dashboard__card-value">
						{{ formatDuration(systemStats.serverUptime) }}
					</div>
				</w-card>

			</section>
			<div class="admin-dashboard__wrapper">
				<section class="admin-dashboard__content">
					
					<VindiDatePicker
						v-model="date"
						range
					/>

					{{ date }}

				</section>
				<aside class="admin-dashboard__sidebar">

					<!-- ANCHOR Active users -->
					<div class="admin-dashboard__sidebar-container admin-dashboard__sidebar-container--users">
						<div class="admin-dashboard__users-inner">
							<div class="admin-dashboard__users-inner-title">
								<VindiTitle icon="mdi mdi-account">
									Users
								</VindiTitle>
								<VindiSpacer />
								<w-button 
									bg-color="transparent"
									color="error"
									route="/admin/users"
								>
									View list
								</w-button>
							</div>
						</div>
						<w-divider />
						<div
							v-if="!activeUsers.authenticatedUsers.length"
							class="admin-dashboard__sidebar-container-users-empty"
						>
							No users online
						</div>
						<div
							v-else
							class="admin-dashboard__sidebar-container-users-list"
						>
							<div
								v-for="profile in activeUsers.authenticatedUsers"
								:key="profile.id"
							>
								<VindiAvatar
									:profile="profile"
									size="40"
								/>
							</div>
						</div>
						<w-divider />
						<div class="admin-dashboard__users-inner">
							<small>
								{{ activeUsers.authenticatedAmount }} known users online
							</small>
							<br>
							<small>
								{{ activeUsers.anonymousAmount }} anonymous users online
							</small>
						</div>
					</div>

					<!-- ANCHOR Analytics -->
					<div class="admin-dashboard__sidebar-container admin-dashboard__sidebar-container-analytics">
						<div class="simple-subtitle">
							Analytics
						</div>
						<w-select
							v-model="analytic"
							class="admin-dashboard__sidebar-analytics--event__selector"
							:items="analyticsList"
						/>
					</div>

					<!-- ANCHOR Maintenance -->
					<div class="admin-dashboard__sidebar-container">
						<div class="simple-subtitle">
							Maintenance
						</div>
						<w-switch />
					</div>

					<!-- ANCHOR Version -->
					<div class="admin-dashboard__sidebar-container">
						<w-flex class="simple-subtitle">
							Version Information
							<VindiSpacer />
							<w-icon
								class="admin-dashboard__version-reload"
								title="Reload version information"
								@click="fetchVersionInfo"
							>
								mdi mdi-reload
							</w-icon>
						</w-flex>

						<div v-if="versionLoading" class="admin-dashboard__version-loading">
							<w-progress circle :size="12" />
							Loading...
						</div>
						<template v-else>
							<div class="admin-dashboard__version-info">
								Vindigo version: <strong>{{ versionInfo.current }}</strong>
							</div>
							<template v-if="versionInfo.update">
								<w-alert info>
									New version available: {{ versionInfo.latest }}
								</w-alert>
								<w-button
									bg-color="primary"
									class="admin-dashboard__update-button"
									:disabled="isUpdating"
									@click="updateVindigo"
								>
									<w-icon class="left">
										mdi mdi-refresh
									</w-icon>
									Update vindigo
								</w-button>
							</template>
							<w-alert
								v-else
								success
								class="nmb"
							>
								Your Vindigo is up-to-date!
							</w-alert>
						</template>
					</div>

				</aside>
			</div>
		</Container>

		<!-- ANCHOR Update dialog -->
		<w-dialog
			v-model="isUpdating"
			class="p-0 text-center py-4 dark:bg-gray-800"
			dialog-class="rounded-xl dark:bg-gray-700"
			width="500px"
			persistent
		>
			Vindigo is updating... Please wait
		</w-dialog>
	</section>
</template>

<script lang="ts">
import AdminVersion from '~/assets/query/admin/adminVersion.gql';
import AdminDashboard from "~/assets/query/admin/adminDashboard.gql";
import updateVersion from "~/assets/query/admin/adminUpdateVersion.gql";
import dayjs from "dayjs";
import Vue from "vue";
import { formatBytes } from '~/src/helpers';

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

	async asyncData(context) {
		const result = await context.$api.query(AdminDashboard);

		return {
			systemStats: result.fetchSystemStats,
			activeUsers: result.activeUsers
		};
	},

	data: () => ({
		anonUsersCount: 0,
		activeUsersCount: 0,
		activeUsers: [] as any[],
		versionLoading: true,
		isUpdating: false,
		systemStats: null,
		versionInfo: {},
		date: [],

		// Analytics
		analytic: 'REQUESTS',
		analyticsList: [
			{ label: 'API Requests', value: 'REQUESTS' },
			{ label: 'Tasks created', value: 'TASKS' },
			{ label: 'Projects created', value: 'PROJECTS' },
		]
	}),

	computed: {
		user(): any {
			return this.$store.state.profile;
		}
	},

	mounted() {
		this.fetchVersionInfo();
	},

	methods: {
		async updateVindigo() {
			this.isUpdating = true;

			// This one is fine
			const request: any = await this.$api.query(updateVersion);
			const version = request.updateVersion;

			if (version) {
				this.$waveui.notify({
					success: true,
					message: "Vindigo has been updated!",
					timeout: 5000,
				});
			} else {
				this.$waveui.notify({
					error: true,
					message: "Something went wrong while updating vindigo",
					timeout: 2500,
				});
			}

			this.isUpdating = false;
			this.fetchVersionInfo();
		},

		formatBytes(value: number): string {
			return formatBytes(value);
		},

		formatDuration(seconds: number): string {
			return dayjs.duration(seconds, 's').humanize();
		},

		async fetchVersionInfo() {
			this.versionLoading = true;

			const request: any = await this.$api.query(AdminVersion);
			const version = request.versionInfo;

			if(version.update) {
				this.$waveui.notify({
					info: true,
					message: `New update available!<div class="admin-version-alert">Version ${version.latest}</div>`,
					icon: 'mdi mdi-upload'
				});
			}

			this.versionLoading = false;
			this.versionInfo = version;
		}
	},
});
</script>

<style lang="scss">
.admin-version-alert {
	@include font-weight(normal);
}

.admin-dashboard {

	/* x axis */
	.frappe-chart .x.axis .line-vertical,
	.frappe-chart .x.axis text {
		display: none;
	}

	/* y axis */
	.frappe-chart .y.axis .line-horizontal,
	.frappe-chart .y.axis text {
		display: none;
	}

	&__header {
		@include margin(6, t);
		@include padding(1, l);
	}

	&__title {
		@include font-size('2xl');
		@include font-weight(medium);
	}

	&__subtitle {
		color: gray;
	}
	
	&__statistics {
		@include margin(6, t);

		gap: 2rem;
		display: grid;
		grid-auto-flow: column;
		grid-auto-columns: 1fr;
	}

	&__card {
		@include shadow;
		@include rounded('2xl');

		color: white;

		$color-map: (
			1: 'info',
			2: 'primary',
			3: 'error',
			4: 'warning',
		);

		@each $index, $color in $color-map {
			&:nth-child(#{$index}) {
				$color-value: map-get($theme-general, $color);

				@include glow(rgba($color-value, 0.6), 0.5);
				background-color: $color-value;
			}
		}
	}

	&__card-name {
		@include font-size(sm);

		opacity: 0.8;
	}

	&__card-value {
		@include font-size('2xl');
	}

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

	&__content {
		@include shadow;
		@include padding(3);
		@include margin(8, t);
		@include rounded('2xl');

		grid-column: 1 / span 3;
		background-color: var(--color-shade-0);
	}

	&__sidebar {
		@include margin(8, t);

		display: flex;
		flex-direction: column;
		gap: 1.75rem;
	}

	&__sidebar-container {
		@include shadow;
		@include padding(3);
		@include rounded('2xl');
		@include dark {
			background-color: var(--color-shade-2);
		}

		width: 100%;
		position: relative;
		background-color: white;

		.w-divider {
			margin: 0;
		}

		.section-title {
			padding: 0;
		}

		&--users {
			padding: 0;
		}
	}

	&__sidebar-container-users-empty {
		@include padding(2, y);

		text-align: center;
		color: gray;
	}

	&__sidebar-container-users-list {
		@include padding(4, x);
		@include padding(2, y);

		gap: 4;
		display: grid;
		grid-template-columns: repeat(5, minmax(0, 1fr));
		justify-items: center;
	}

	&__users-inner {
		@include padding(3);
	}

	&__users-inner-title {
		display: flex;
	}

	&__version-reload {
		cursor: pointer;
	}

	&__version-loading {
		color: gray;
		display: flex;
		gap: 0.5rem;
		align-items: center;
	}

	&__version-info strong {
		@include font-weight(medium);
	}

	&__update-button {
		width: 100%;
	}
}
</style>