<template>
	<section class="project-tasks">
		<div v-if="!tasks.length" class="project-view-empty">
			<ProjectTasksEmptyGraphic
				:color="project.accentColor"
			/>
			<h2>
				Manage your tasks
			</h2>
			<p>
				Add tasks to your project to track individual goals and objectives
			</p>
			<w-button
				bg-color="primary"
				color="white"
				@click="openTaskCreator"
			>
				Create task
				<w-icon class="right">
					mdi mdi-plus
				</w-icon>
			</w-button>
		</div>

		<Container v-else class="project-tasks__content">
			<section
				v-if="pinned.length > 0"
				class="project-tasks__pinned"
			>
				<VindiTitle icon="mdi mdi-pin">
					Pinned tasks
				</VindiTitle>
				<div class="project-tasks__pinned-list">
					<TaskTile
						v-for="task in pinned"
						:key="task.id"
						:task="task"
					/>
				</div>
			</section>

			<section>
				<VindiTitle icon="mdi mdi-clipboard-check-outline">
					Tasks overview
				</VindiTitle>
				<div class="project-tasks__list">
					<div class="project-tasks__header">
						<div>
							<div class="simple-subtitle">
								Sorting
							</div>
							<w-select
								v-model="sortMethod"
								:items="sortMethods"
								bg-color="transparent"
							/>
						</div>
						<w-divider vertical />
						<div>
							<div class="simple-subtitle">
								Filters
							</div>
							<w-flex :gap="5">
								<div class="project-tasks__filter">
									Creator
									<w-icon>
										mdi mdi-chevron-down
									</w-icon>
								</div>
								<div class="project-tasks__filter">
									Label
									<w-icon>
										mdi mdi-chevron-down
									</w-icon>
								</div>
								<div class="project-tasks__filter">
									List
									<w-icon>
										mdi mdi-chevron-down
									</w-icon>
								</div>
								<div class="project-tasks__filter">
									Assignee
									<w-icon>
										mdi mdi-chevron-down
									</w-icon>
								</div>
							</w-flex>
						</div>
						<w-divider vertical />
						<VindiSpacer />
						<w-input
							v-model="taskSearch"
							class="project-tasks__search"
							inner-icon-left="mdi mdi-magnify"
							placeholder="Search task..."
							bg-color="shade-3"
							autocomplete="off"
							color="#eee"
							name="search"
						/>
					</div>
					<w-divider class="nm" />
					<w-table
						:headers="headers"
						:items="tasksList"
						no-headers
					>
						<template #[`item-cell.id`]="{ item }">
							<div
								class="project-tasks__id"
								:style="taskIdStyle"
								@click="openTask(item)"
							>
								#{{ item.id }}
							</div>
						</template>

						<template #[`item-cell.summary`]="{ item }">
							<div class="project-tasks__title">
								<div
									class="project-tasks__summary"
									@click="openTask(item)"
								>
									{{ item.summary }}
								</div>
								<div class="project-tasks__labels">
									<TaskLabel
										v-for="label in item.labels"
										:key="label.id"
										:value="label"
									/>
								</div>
							</div>
							<div
								class="project-tasks__status"
							>
								Created by {{ item.creator.fullName }}
							</div>
						</template>

						<template #[`item-cell.members`]="{ item }">
							<VindiAvatar
								v-for="member in item.assignees"
								:key="member.id"
								:profile="member"
								:show-border="false"
								:size="32"
							/>
						</template>

						<template #[`item-cell.options`]>
							<w-icon>
								mdi mdi-message
							</w-icon>
						</template>

						<template #no-data>
							No tasks match your search criteria
						</template>
					</w-table>
					<w-divider class="nm" />
					<VindiPagination
						v-model="currentPage"
						:total="pageCount"
						:visible="5"
						class="project-tasks__pagination"
					/>
				</div>
			</section>
		</Container>
	</section>
</template>

<script lang="ts">
import Vue from 'vue';
import dayjs from 'dayjs';
import gql from 'graphql-tag';
import { chunk } from 'lodash';
import { parseSlug } from '~/src/helpers';
import fetchTasksPage from '~/assets/query/tasks/fetchTasksPage.gql';

export default Vue.extend({

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

		return {
			project: result.project,
			pinned: result.project.pinnedTasks,
			tasks: result.project.tasks
		};
	},

	data: () => ({
		project: null as any,
		pinned: [] as any[],
		tasks: [] as any[],
		manager: null as any,
		currentPage: 0,
		tasksPerPage: 10,
		taskSearch: '',

		// Sorting,
		sortMethod: 'MODIFIED',
		sortMethods: [
			{ label: 'Last modified', value: 'MODIFIED' },
			{ label: 'Last created', value: 'CREATED' },
			{ label: 'Alphabetical', value: 'ALPHABETICAL' },
			{ label: 'Due date', value: 'DUE_DATE' }
		],
		sortFunctions: {
			MODIFIED: 'sortTasksModified',
			CREATED: 'sortTasksCreated',
			ALPHABETICAL: 'sortTasksAlphabetical',
			DUE_DATE: 'sortTasksDueDate'
		} as any,

		// Headers
		headers: [
			{ key: 'id' },
			{ key: 'summary' },
			{ key: 'members' },
			{ key: 'options' }
		],
	}),

	computed: {
		taskIdStyle(): any {
			return {
				color: this.project.accentColor
			};
		},

		tasksFiltered() {
			const search = this.taskSearch.toLowerCase();
			const method = this.sortFunctions[this.sortMethod];
			const func = (this as any)[method];

			if(!func) {
				throw new Error('Unexpected sort method');
			}

			return [
				...this.tasks
			].filter((task) => {
				return task.summary.toLowerCase().includes(search);
			}).sort(func);
		},

		pageCount(): number {
			return Math.ceil(this.tasksFiltered.length / this.tasksPerPage);
		},

		tasksList(): any[] {
			return chunk(this.tasksFiltered, this.tasksPerPage)[this.currentPage] || [];
		},
	},

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

		const slug = parseSlug(this.$route.params.pid);

		// Create a simple subscription to detect
		// modifications made to project tasks.
		function createQuery(field: string): any {
			return gql`
				subscription ($pid: Int!) {
					${field}(projectId: $pid) {
						id
					}
				}
			`;
		}
		
		this.manager.subscribe({
			query: createQuery('taskCreated'),
			next: this.refetchTasks,
			variables: {
				pid: slug
			}
		});

		this.manager.subscribe({
			query: createQuery('taskUpdated'),
			next: this.refetchTasks,
			variables: {
				pid: slug
			}
		});

		this.manager.subscribe({
			query: createQuery('taskRemoved'),
			next: this.refetchTasks,
			variables: {
				pid: slug
			}
		});
	},

	destroyed() {
		this.manager?.dispose();
	},

	methods: {

		sortTasksModified(left: any, right: any): number {
			const aModified = dayjs(parseInt(left.lastModifiedAt));
			const bModified = dayjs(parseInt(right.lastModifiedAt));

			return aModified.isBefore(bModified) ? 1 : -1;
		},

		sortTasksCreated(left: any, right: any): number {
			const aCreated = dayjs(parseInt(left.createdAt));
			const bCreated = dayjs(parseInt(right.createdAt));

			return aCreated.isBefore(bCreated) ? 1 : -1;
		},

		sortTasksAlphabetical(left: any, right: any): number {
			return left.summary.localeCompare(right.summary);
		},

		sortTasksDueDate(left: any, right: any): number {
			const aTime = dayjs(parseInt(left.endTime || '0'));
			const bTime = dayjs(parseInt(right.endTime || '0'));

			return aTime.isBefore(bTime) ? 1 : -1;
		},

		async refetchTasks() {
			const res = await this.$api.query(fetchTasksPage, {
				pid: this.project.id
			});

			this.pinned = res.project.pinnedTasks;
			this.tasks = res.project.tasks;
		},

		formatDate(task: any): string {
			const lastModified = parseInt(task.lastModifiedAt);
			const dateFormat = this.$t('FULL_DATE_FORMAT') as string;

			return dayjs(lastModified).format(dateFormat);
		},

		openTask(task: any) {
			this.$store.dispatch('openTaskViewer', task.id);
		}

	}
});
</script>

<style lang="scss">
.project-tasks {

	&__content {
		@include margin(16, t);
	}

	&__pinned {
		@include margin(12, b);
	}

	&__pinned-list {
		@include margin(2, t);

		display: grid;
		gap: 0.5rem;

		@include breakpoint(lg) {
			grid-template-columns: repeat(4, minmax(0, 1fr));
		}
	}

	&__list {
		@include shadow;
		@include rounded('3xl');
		@include margin(2, t);
		
		background-color: var(--color-shade-0);
		min-height: 250px;
	}

	&__header {
		@include padding(4);

		display: flex;

		.simple-subtitle {
			padding-bottom: 0;
		}

		.w-select__selection-wrap, input {
			padding-right: 0;
			padding-left: 0;
		}
	}

	&__filter {
		@include margin(3.5, t);
		@include font-weight(medium);

		cursor: pointer;
	}

	&__search {
		max-width: 20rem;
	}

	.w-table__cell {
		height: 4.5rem;

		&:first-child {
			@include padding(5, r);

			width: 0;
		}

		&:last-child {
			@include padding(0, l);

			width: 0;
			color: gray;
		}
	}

	&__id {
		@include font-weight(bold);
		@include font-size(lg);

		cursor: pointer;
	}

	&__title {
		display: flex;
		align-items: center;
	}

	&__summary {
		@include padding(2, r);
		@include truncate;

		cursor: pointer;
	}

	&__labels {
		display: flex;
		gap: 0.25rem;
	}

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

		color: gray;
	}

	&__pagination {
		@include padding(4);
	}
}
</style>