<template>
	<div>
		<n-card class="settings-card">
			<ObjectList :options="listOptions" />
		</n-card>

		<!-- 创建角色弹窗 -->
		<n-modal
			v-model:show="showCreateRoleDialog"
			preset="card"
			:title="$t('Create Role')"
			:style="modalStyle"
			:mask-closable="true"
			:close-on-esc="true"
			class="create-role-modal"
		>
			<template #header>
				<span class="text-lg font-semibold">{{ $t('Create Role') }}</span>
			</template>
			<n-space vertical :size="20">
				<n-form-item :label="$t('Role')" :required="true">
					<n-input
						v-model:value="newRoleTitle"
						placeholder=""
						:size="inputSize"
						class="w-full"
						@keyup.enter="handleCreateRole"
					/>
				</n-form-item>
			</n-space>
			<template #action>
				<n-space :vertical="isMobile" :size="isMobile ? 12 : 16" class="w-full">
					<n-button @click="showCreateRoleDialog = false" :block="isMobile" :size="buttonSize">
						{{ $t('Cancel') }}
					</n-button>
					<n-button
						type="primary"
						:loading="createRoleLoading"
						:disabled="!newRoleTitle"
						@click="handleCreateRole"
						:block="isMobile"
						:size="buttonSize"
					>
						{{ $t('Confirm') }}
					</n-button>
				</n-space>
			</template>
		</n-modal>

		<!-- 删除角色确认弹窗 -->
		<n-modal
			v-model:show="showDeleteRoleDialog"
			preset="dialog"
			:title="$t('Delete Role')"
			:positive-text="$t('Delete')"
			:positive-button-props="{ type: 'error' }"
			:loading="deleteRoleLoading"
			:mask-closable="true"
			:close-on-esc="true"
			@positive-click="handleDeleteRole"
		>
			<div class="py-4">
				<p class="text-base" v-html="$t('Are you sure you want to delete role <b>{role}</b>?', { role: selectedRole?.title || '' })"></p>
			</div>
		</n-modal>
	</div>
</template>

<script setup lang="jsx">
import { h, ref, getCurrentInstance, computed, onMounted, onBeforeUnmount } from 'vue';
import { toast } from 'vue-sonner';
import { FeatherIcon } from 'jingrow-ui';
import { NCard, NModal, NSpace, NFormItem, NInput, NButton } from 'naive-ui';
import { icon, renderDialog } from '../../utils/components';
import ObjectList from '../ObjectList.vue';
import RoleConfigureDialog from './RoleConfigureDialog.vue';
import { useRouter } from 'vue-router';
import UserAvatarGroup from '../AvatarGroup.vue';
import { getToastErrorMessage } from '../../utils/toast';

const instance = getCurrentInstance();
const $t = instance?.appContext.config.globalProperties.$t || ((key) => key);
const router = useRouter();

const listOptions = ref({
	pagetype: 'Jcloud Role',
	fields: [
		{ users: ['user', 'user.full_name', 'user.user_image'] },
		'admin_access',
	],
	documentation: 'https://jingrow.com/docs/role-permissions',
	columns: [
		{
			label: $t('Role'),
			fieldname: 'title',
			width: 1,
			suffix: (row) => {
				return row.admin_access ? (
					<FeatherIcon name="shield" class="ml-1 h-4 w-4 text-gray-700" />
				) : null;
			},
		},
		{
			label: $t('Members'),
			type: 'Component',
			component: ({ row }) => {
				return (
					<div
						onClick={(e) => {
							e.preventDefault();
							configureRole(row);
						}}
						class="flex h-6 items-center space-x-2"
					>
						<UserAvatarGroup users={row.users} />
						<Button label={$t('Add Member')}>
							{{ icon: () => <i-lucide-plus class="h-4 w-4 text-gray-600" /> }}
						</Button>
					</div>
				);
			},
			width: 1,
		},
	],
	rowActions({ row, listResource: roleListResource }) {
		return [
			{
				label: $t('Edit Permissions'),
				onClick() {
					router.push({
						name: 'SettingsPermissionRolePermissions',
						params: { roleId: row.name },
					});
				},
			},
			{
				label: $t('Configure Role'),
				onClick: () => configureRole(row),
			},
			{
				label: $t('Delete Role'),
				onClick() {
					if (roleListResource.delete.loading) return;
					selectedRole.value = row;
					roleListResourceRef.value = roleListResource;
					showDeleteRoleDialog.value = true;
				},
			},
		];
	},
	route(row) {
		return {
			name: 'SettingsPermissionRolePermissions',
			params: { roleId: row.name },
		};
	},
	primaryAction({ listResource: groups }) {
		roleListResourceRef.value = groups;
		return {
			label: $t('New Role'),
			slots: {
				prefix: icon('plus'),
			},
			onClick() {
				newRoleTitle.value = '';
				showCreateRoleDialog.value = true;
			},
		};
	},
});

const windowWidth = ref(window.innerWidth);
const showCreateRoleDialog = ref(false);
const showDeleteRoleDialog = ref(false);
const newRoleTitle = ref('');
const selectedRole = ref(null);
const roleListResourceRef = ref(null);
const createRoleLoading = ref(false);
const deleteRoleLoading = ref(false);

const isMobile = computed(() => windowWidth.value <= 768);
const modalStyle = computed(() => ({
	width: isMobile.value ? '95vw' : '700px',
	maxWidth: isMobile.value ? '95vw' : '90vw',
}));
const inputSize = computed(() => isMobile.value ? 'medium' : 'large');
const buttonSize = computed(() => isMobile.value ? 'medium' : 'medium');

function handleResize() {
	windowWidth.value = window.innerWidth;
}

onMounted(() => {
	window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
	window.removeEventListener('resize', handleResize);
});

async function handleCreateRole() {
	if (!newRoleTitle.value || !roleListResourceRef.value) return;
	if (createRoleLoading.value) return;
	
	createRoleLoading.value = true;
	try {
		await roleListResourceRef.value.insert.submit({ title: newRoleTitle.value });
		toast.success($t('Role created successfully'));
		showCreateRoleDialog.value = false;
		newRoleTitle.value = '';
	} catch (error) {
		toast.error(getToastErrorMessage(error));
	} finally {
		createRoleLoading.value = false;
	}
}

async function handleDeleteRole() {
	if (!selectedRole.value || !roleListResourceRef.value) return;
	if (deleteRoleLoading.value) return;
	
	const roleTitle = selectedRole.value.title;
	deleteRoleLoading.value = true;
	try {
		await toast.promise(
			roleListResourceRef.value.delete.submit(selectedRole.value.name),
			{
				loading: $t('Deleting role...'),
				success: () => {
					roleListResourceRef.value.reload();
					showDeleteRoleDialog.value = false;
					selectedRole.value = null;
					return $t('Role {role} deleted', { role: roleTitle });
				},
				error: (e) => getToastErrorMessage(e),
			}
		);
	} finally {
		deleteRoleLoading.value = false;
	}
}

function configureRole(row) {
	renderDialog(h(RoleConfigureDialog, { roleId: row.name }));
}
</script>

<style scoped>
.settings-card {
	border-radius: 12px;
	box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
	transition: box-shadow 0.2s ease;
}

.settings-card:hover {
	box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

:deep(.create-role-modal .n-card) {
	width: 700px;
	max-width: 90vw;
}

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

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

:deep(.create-role-modal .n-input) {
	width: 100%;
}

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

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

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

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

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

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