<template>
	<n-modal
		v-model:show="showDialog"
		preset="card"
		:title="$t('Add New Member')"
		:style="modalStyle"
		:mask-closable="true"
		:close-on-esc="true"
		class="invite-member-modal"
	>
		<template #header>
			<span class="text-lg font-semibold">{{ $t('Add New Member') }}</span>
		</template>
		<n-space vertical :size="20">
			<n-form-item :label="$t('Username')" :required="true">
				<n-input
					v-model:value="username"
					placeholder=""
					:size="inputSize"
					class="w-full"
				/>
			</n-form-item>
			<div v-if="$resources.roles.data?.length > 0" class="space-y-4">
				<div class="role-select-row">
					<label class="role-select-label">{{ $t('Select Role') }}</label>
					<div class="flex items-center gap-2">
						<n-select
							v-model:value="selectedRole"
							:options="roleOptions"
							placeholder=""
							:size="inputSize"
							class="flex-1"
						/>
						<n-button
							type="primary"
							:disabled="!selectedRole"
							@click="addRole"
							:size="buttonSize"
						>
							<template #icon>
								<n-icon><PlusIcon /></n-icon>
							</template>
							{{ $t('Add') }}
						</n-button>
					</div>
				</div>
				<div v-if="selectedRoles.length > 0" class="space-y-2">
					<div
						v-for="role in selectedRoles"
						:key="role.value"
						class="flex items-center justify-between p-3 rounded border border-gray-200 bg-gray-50"
					>
						<div class="text-base text-gray-800">{{ role.label }}</div>
						<n-button
							tertiary
							circle
							size="small"
							@click="removeRole(role.value)"
						>
							<template #icon>
								<n-icon><XIcon /></n-icon>
							</template>
						</n-button>
					</div>
				</div>
			</div>
			<n-alert
				v-if="$team?.inviteTeamMember?.error"
				type="error"
				:title="getErrorMessage($team?.inviteTeamMember?.error)"
			/>
		</n-space>
		<template #action>
			<n-space :vertical="isMobile" :size="isMobile ? 12 : 16" class="w-full">
				<n-button @click="hide" :block="isMobile" :size="buttonSize">
					{{ $t('Cancel') }}
				</n-button>
				<n-button
					type="primary"
					:loading="$team?.inviteTeamMember?.loading"
					@click="inviteMember"
					:block="isMobile"
					:size="buttonSize"
				>
					{{ $t('Invite Member') }}
				</n-button>
			</n-space>
		</template>
	</n-modal>
</template>

<script>
import {
	NModal,
	NFormItem,
	NInput,
	NSpace,
	NAlert,
	NButton,
	NSelect,
	NIcon,
} from 'naive-ui';
import { toast } from 'vue-sonner';
import PlusIcon from '~icons/lucide/plus';
import XIcon from '~icons/lucide/x';

export default {
	components: {
		NModal,
		NFormItem,
		NInput,
		NSpace,
		NAlert,
		NButton,
		NSelect,
		NIcon,
		PlusIcon,
		XIcon,
	},
	emits: ['success', 'update:modelValue'],
	props: {
		modelValue: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			username: '',
			selectedRoles: [],
			selectedRole: null,
			windowWidth: window.innerWidth,
		};
	},
	computed: {
		showDialog: {
			get() {
				return this.modelValue;
			},
			set(value) {
				this.$emit('update:modelValue', value);
			}
		},
		isMobile() {
			return this.windowWidth <= 768;
		},
		modalStyle() {
			return {
				width: this.isMobile ? '95vw' : '700px',
				maxWidth: this.isMobile ? '95vw' : '90vw',
			};
		},
		inputSize() {
			return this.isMobile ? 'medium' : 'large';
		},
		buttonSize() {
			return this.isMobile ? 'medium' : 'large';
		},
		roleOptions() {
			if (!this.$resources.roles.data) return [];
			return this.$resources.roles.data
				.filter((role) => {
					return !this.selectedRoles.some(
						(selectedRole) => selectedRole.value === role.name,
					);
				})
				.map((role) => ({
					label: role.title,
					value: role.name,
				}));
		},
	},
	mounted() {
		this.handleResize();
		window.addEventListener('resize', this.handleResize);
	},
	beforeUnmount() {
		window.removeEventListener('resize', this.handleResize);
	},
	methods: {
		handleResize() {
			this.windowWidth = window.innerWidth;
		},
		getErrorMessage(error) {
			if (!error) return '';
			try {
				if (typeof error === 'string') return error;
				if (error && typeof error === 'object') {
					if (error.message) return error.message;
					if (error.messages && Array.isArray(error.messages)) {
						return error.messages.join('\n');
					}
				}
				return String(error);
			} catch (e) {
				return String(error || 'Unknown error');
			}
		},
		addRole() {
			if (this.selectedRole) {
				const role = this.$resources.roles.data.find(r => r.name === this.selectedRole);
				if (role) {
					this.selectedRoles.push({
						label: role.title,
						value: role.name,
					});
					this.selectedRole = null;
				}
			}
		},
		removeRole(roleToRemove) {
			this.selectedRoles = this.selectedRoles.filter(
				(role) => role.value !== roleToRemove,
			);
		},
		async inviteMember() {
			if (!this.username) {
				toast.error(this.$t('Username is required'));
				return;
			}
			if (!this.$team?.inviteTeamMember) {
				toast.error(this.$t('Team service is not available'));
				return;
			}
			if (this.$team.inviteTeamMember.loading) return;
			
			try {
				await this.$team.inviteTeamMember.submit({
					username: this.username,
					roles: this.selectedRoles.map((role) => role.value),
				});
				toast.success(this.$t('Member added to team'), { duration: 2000 });
				this.hide();
				setTimeout(() => {
					if (this.$team?.getTeamMembers) {
						this.$team.getTeamMembers.submit();
					}
					this.$emit('success');
				}, 500);
			} catch (error) {
				// Error will be displayed in the alert component
				console.error('Failed to invite team member:', error);
			}
		},
		hide() {
			this.showDialog = false;
			this.username = '';
			this.selectedRoles = [];
			this.selectedRole = null;
		}
	},
	resources: {
		roles() {
			return {
				type: 'list',
				pagetype: 'Jcloud Role',
				fields: ['name', 'title'],
				initialData: [],
				auto: true,
			};
		},
	}
};
</script>

<style scoped>
:deep(.invite-member-modal .n-card) {
	width: 700px;
	max-width: 90vw;
}

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

:deep(.invite-member-modal .n-form-item) {
	margin-bottom: 0;
}

:deep(.invite-member-modal .n-input),
:deep(.invite-member-modal .n-select) {
	width: 100%;
}

.role-select-row {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.role-select-label {
	font-size: 14px;
	font-weight: 500;
	color: var(--n-text-color);
	margin-bottom: 0;
}

.role-select-row .flex {
	display: flex;
	align-items: center;
	gap: 8px;
}

.role-select-row .n-select {
	flex: 1;
}

:deep(.invite-member-modal .n-card__action) {
	padding: 16px 24px;
}

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

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

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

	:deep(.invite-member-modal .n-card__action) {
		padding: 12px 16px;
	}

	:deep(.invite-member-modal .n-button) {
		width: 100%;
		font-size: 16px;
		height: 44px;
	}
}
</style>
