<template>
	<Dialog
		:options="{
			title: $t('Add New Member'),
			actions: [
				{
					label: $t('Invite Member'),
					variant: 'solid',
					onClick: inviteMember,
				},
			],
		}"
		v-model="show"
	>
		<template #body-content>
			<div class="space-y-4">
				<FormControl :label="$t('Username')" v-model="username" />
				<div
					v-if="$resources.roles.data?.length > 0"
					class="flex items-center space-x-2"
				>
					<FormControl
						class="w-full"
						type="autocomplete"
						:label="$t('Select Role')"
						:options="roleOptions"
						v-model="selectedRole"
					/>
					<Button
						:label="$t('Add')"
						icon-left="plus"
						:disabled="!selectedRole"
						@click="addRole"
						class="mt-5"
					/>
				</div>
				<div
					v-if="selectedRoles.length > 0"
					class="divide-y rounded border border-gray-300 px-1.5"
				>
					<div
						class="flex w-full items-center space-x-2 py-1.5"
						v-for="role in selectedRoles"
					>
						<div class="flex w-full items-center justify-between px-3 py-2">
							<div class="text-base text-gray-800">{{ role.label }}</div>
						</div>
						<Button
							class="ml-auto"
							variant="ghost"
							icon="x"
							@click="removeRole(role.value)"
						/>
					</div>
				</div>
			</div>
		</template>
	</Dialog>
</template>

<script>
import { toast } from 'vue-sonner';

export default {
	data() {
		return {
			username: '',
			show: true,
			selectedRoles: [],
			selectedRole: null,
		};
	},
	resources: {
		roles() {
			return {
				type: 'list',
				pagetype: 'Jcloud Role',
				fields: ['name', 'title'],
				initialData: [],
				auto: true,
			};
		},
	},
	computed: {
		roleOptions() {
			return this.$resources.roles.data
				.filter((role) => {
					return !this.selectedRoles.some(
						(selectedRole) => selectedRole.value === role.name,
					);
				})
				.map((role) => ({
					label: role.title,
					value: role.name,
				}));
		},
	},
	methods: {
		addRole() {
			if (this.selectedRole) {
				this.selectedRoles.push(this.selectedRole);
				this.selectedRole = null;
			}
		},
		removeRole(roleToRemove) {
			this.selectedRoles = this.selectedRoles.filter(
				(role) => role.value !== roleToRemove,
			);
		},
		inviteMember() {
			if (!this.username) {
				toast.error(this.$t('Username is required'));
				return;
			}
			if (this.$team.inviteTeamMember.loading) return;
			
			toast.success(this.$t('Member added to team'), { duration: 2000 });
			this.show = false;
			this.$team.inviteTeamMember.submit({
				username: this.username,
				roles: this.selectedRoles.map((role) => role.value),
			});
			this.username = '';
			this.selectedRoles = [];
			setTimeout(() => {
				if (this.$team?.getTeamMembers) {
					this.$team.getTeamMembers.submit();
				}
			}, 500);
		},
	},
};
</script>