<template>
	<n-modal
		v-if="role"
		v-model:show="show"
		preset="card"
		:title="role.title"
		:style="modalStyle"
		:mask-closable="true"
		:close-on-esc="true"
		class="role-configure-modal"
	>
		<template #header>
			<span class="text-lg font-semibold">{{ role.title }}</span>
		</template>
		<n-tabs v-model:value="activeTab" type="line" animated>
			<n-tab-pane name="members" :tab="$t('Members')">
				<n-space vertical :size="20">
					<div class="flex gap-2 items-end">
						<n-select
							v-model:value="selectedMember"
							:options="autoCompleteList"
							:placeholder="$t('Select member to add')"
							:size="inputSize"
							class="flex-1"
							filterable
						/>
						<n-button
							type="primary"
							:disabled="!selectedMember"
							:loading="$resources.role.addUser?.loading"
							@click="() => addUser(selectedMember)"
							:size="buttonSize"
						>
							{{ $t('Add Member') }}
						</n-button>
					</div>
					<n-card>
						<div class="mb-3 text-gray-600 font-medium">{{ $t('Members') }}</div>
						<div
							v-if="roleUsers.length === 0"
							class="p-6 text-center text-gray-500"
						>
							<span>{{ $t('No members have been added to this role yet.') }}</span>
						</div>
						<div v-else class="space-y-2">
							<div
								v-for="user in roleUsers"
								:key="user.user"
								class="flex justify-between items-center py-2 border-b border-gray-100 last:border-0"
							>
								<UserWithAvatarCell
									:avatarImage="user.user_image"
									:fullName="user.full_name"
									:email="user.user"
								/>
								<n-button
									tertiary
									circle
									size="small"
									@click="() => removeUser(user.user)"
								>
									<template #icon>
										<n-icon><XIcon /></n-icon>
									</template>
								</n-button>
							</div>
						</div>
					</n-card>
				</n-space>
			</n-tab-pane>
			<n-tab-pane name="settings" :tab="$t('Settings')">
				<n-space vertical :size="8">
					<n-card>
						<n-form-item>
							<div class="flex items-center justify-between w-full">
								<div class="flex-1">
									<div class="text-base font-medium text-gray-900 mb-1">
										{{ $t('Admin Access') }}
									</div>
									<div class="text-sm text-gray-600">
										{{ $t('Grant members permissions similar to team owner. Includes access to all pages and settings.') }}
									</div>
								</div>
								<n-switch
									:value="adminAccess"
									@update:value="(val) => adminAccess = val"
									size="medium"
								/>
							</div>
						</n-form-item>
					</n-card>
					<n-card>
						<h2 class="mb-2 text-base font-semibold">{{ $t('Page Access Permissions') }}</h2>
						<div class="permissions-list">
							<div class="permission-item">
								<span class="text-base">{{ $t('Allow Billing Access') }}</span>
								<n-switch
									:value="allowBilling"
									@update:value="(val) => allowBilling = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
							<div class="permission-item">
								<span class="text-base">{{ $t('Allow Apps Access') }}</span>
								<n-switch
									:value="allowApps"
									@update:value="(val) => allowApps = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
							<div v-if="$team.pg.jerp_partner" class="permission-item">
								<span class="text-base">{{ $t('Allow Partner Access') }}</span>
								<n-switch
									:value="allowPartner"
									@update:value="(val) => allowPartner = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
							<div class="permission-item">
								<span class="text-base">{{ $t('Allow Site Creation') }}</span>
								<n-switch
									:value="allowSiteCreation"
									@update:value="(val) => allowSiteCreation = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
							<div class="permission-item">
								<span class="text-base">{{ $t('Allow Release Group Creation') }}</span>
								<n-switch
									:value="allowBenchCreation"
									@update:value="(val) => allowBenchCreation = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
							<div class="permission-item">
								<span class="text-base">{{ $t('Allow Server Creation') }}</span>
								<n-switch
									:value="allowServerCreation"
									@update:value="(val) => allowServerCreation = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
							<div class="permission-item">
								<span class="text-base">{{ $t('Allow Webhook Configuration') }}</span>
								<n-switch
									:value="allowWebhookConfiguration"
									@update:value="(val) => allowWebhookConfiguration = val"
									:disabled="adminAccess"
									size="medium"
								/>
							</div>
						</div>
					</n-card>
				</n-space>
			</n-tab-pane>
		</n-tabs>
	</n-modal>
</template>

<script>
import {
	NModal,
	NTabs,
	NTabPane,
	NSpace,
	NSelect,
	NButton,
	NIcon,
	NCard,
	NFormItem,
	NSwitch,
} from 'naive-ui';
import { toast } from 'vue-sonner';
import UserWithAvatarCell from '../UserWithAvatarCell.vue';
import XIcon from '~icons/lucide/x';

export default {
	props: {
		roleId: { type: String, required: true },
	},
	components: {
		UserWithAvatarCell,
		NModal,
		NTabs,
		NTabPane,
		NSpace,
		NSelect,
		NButton,
		NIcon,
		NCard,
		NFormItem,
		NSwitch,
		XIcon,
	},
	data() {
		return {
			selectedMember: null,
			show: true,
			activeTab: 'members',
			windowWidth: window.innerWidth,
		};
	},
	resources: {
		role() {
			return {
				type: 'document',
				pagetype: 'Jcloud Role',
				name: this.roleId,
				whitelistedMethods: {
					addUser: 'add_user',
					removeUser: 'remove_user',
					bulkDelete: 'delete_permissions',
				},
			};
		},
	},
	computed: {
		role() {
			return this.$resources.role.pg;
		},
		roleUsers() {
			return this.role?.users || [];
		},
		autoCompleteList() {
			const isNotGroupMember = (u) =>
				!this.roleUsers.map(({ user }) => user).includes(u);
			return this.$team.pg.team_members
				?.filter(({ user }) => isNotGroupMember(user))
				.map(({ user }) => ({ label: user, value: user }));
		},
		isMobile() {
			return this.windowWidth <= 768;
		},
		modalStyle() {
			return {
				width: this.isMobile ? '95vw' : '900px',
				maxWidth: this.isMobile ? '95vw' : '90vw',
			};
		},
		inputSize() {
			return this.isMobile ? 'medium' : 'large';
		},
		buttonSize() {
			return this.isMobile ? 'medium' : 'medium';
		},
		adminAccess: {
			get() {
				return !!this.role?.admin_access;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						admin_access: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowBilling: {
			get() {
				return !!this.role?.allow_billing;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_billing: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowApps: {
			get() {
				return !!this.role?.allow_apps;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_apps: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowPartner: {
			get() {
				return !!this.role?.allow_partner;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_partner: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowSiteCreation: {
			get() {
				return !!this.role?.allow_site_creation;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_site_creation: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowBenchCreation: {
			get() {
				return !!this.role?.allow_bench_creation;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_bench_creation: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowServerCreation: {
			get() {
				return !!this.role?.allow_server_creation;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_server_creation: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
		allowWebhookConfiguration: {
			get() {
				return !!this.role?.allow_webhook_configuration;
			},
			set(value) {
				this.$resources.role.setValue.submit(
					{
						allow_webhook_configuration: value,
					},
					{ onSuccess: this.$session.roles.reload },
				);
			},
		},
	},
	methods: {
		handleResize() {
			this.windowWidth = window.innerWidth;
		},
		addUser(user) {
			if (!user) return;
			if (this.$resources.role.addUser.loading) return;
			
			toast.success(this.$t('Added {user} to {role}', { user, role: this.role.title }), { duration: 2000 });
			this.selectedMember = null;
			this.$resources.role.addUser.submit({ user });
			setTimeout(() => {
				if (this.$resources.role) {
					this.$resources.role.reload();
				}
			}, 500);
		},
		removeUser(user) {
			if (!user) return;
			if (this.$resources.role.removeUser.loading) return;
			
			toast.success(this.$t('Removed {user} from {role}', { user, role: this.role.title }), { duration: 2000 });
			this.$resources.role.removeUser.submit({ user });
			setTimeout(() => {
				if (this.$resources.role) {
					this.$resources.role.reload();
				}
			}, 500);
		},
	},
	mounted() {
		this.handleResize();
		window.addEventListener('resize', this.handleResize);
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.handleResize);
	},
};
</script>

<style scoped>
:deep(.role-configure-modal .n-card) {
	width: 900px;
	max-width: 90vw;
}

:deep(.role-configure-modal .n-card-body) {
	padding: 24px;
}

:deep(.role-configure-modal .n-tabs) {
	margin-top: 0;
}

:deep(.role-configure-modal .n-tab-pane) {
	padding: 20px 0;
}

:deep(.role-configure-modal .n-card-body) {
	padding: 12px 24px;
}

.permissions-list {
	display: flex;
	flex-direction: column;
}

.permission-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 8px 12px;
	margin: 0 -12px;
	border-radius: 4px;
}

.permission-item:nth-child(even) {
	background-color: #f9fafb;
}

.permission-item:nth-child(odd) {
	background-color: transparent;
}

.permission-item:hover {
	background-color: #f3f4f6;
}

:deep(.role-configure-modal .n-switch) {
	transition: all 0.2s ease;
}

@media (max-width: 768px) {
	:deep(.role-configure-modal .n-card) {
		width: 95vw !important;
		max-width: 95vw !important;
		margin: 20px auto;
		border-radius: 12px;
	}

	:deep(.role-configure-modal .n-card-body) {
		padding: 20px 16px;
	}

	:deep(.role-configure-modal .n-card__header) {
		padding: 16px;
		font-size: 18px;
	}

	:deep(.role-configure-modal .n-tab-pane) {
		padding: 16px 0;
	}
}
</style>
