<template>
	<div>
		<div class="mb-5 flex items-center gap-2">
			<n-tooltip>
				<template #trigger>
					<n-button
						quaternary
						@click="router.push({ name: 'SettingsPermissionRoles' })"
					>
						<template #icon>
							<n-icon><ArrowLeftIcon /></n-icon>
						</template>
					</n-button>
				</template>
				{{ $t('All Roles') }}
			</n-tooltip>
			<h3 class="text-lg font-medium text-gray-900">
				{{ role.pg?.title }}
			</h3>
			<n-tooltip v-if="role.pg?.admin_access">
				<template #trigger>
					<n-icon class="h-5 w-5 text-gray-700">
						<ShieldIcon />
					</n-icon>
				</template>
				{{ $t('Admin Role') }}
			</n-tooltip>
		</div>
		<n-card class="settings-card">
			<ObjectList
				:options="rolePermissions"
				@update:selections="(e) => (selectedItems = e)"
			>
				<template #header-left="{ listResource }">
					<n-dropdown 
						:options="getDropdownOptions(listResource)" 
						trigger="click"
						@select="(key) => handleDropdownSelect(key, listResource)"
					>
					<n-button>
						<template #icon>
							<n-icon><AppWindowIcon /></n-icon>
						</template>
						<span class="flex items-center gap-2">
							{{ currentDropdownOption.label }}
							<n-icon class="ml-1"><ChevronDownIcon /></n-icon>
						</span>
					</n-button>
					</n-dropdown>
				</template>
			</ObjectList>
		</n-card>

		<!-- 添加权限弹窗 -->
		<n-modal
			v-model:show="showAddPermissionDialog"
			preset="card"
			:title="$t('Add Permission')"
			:style="modalStyle"
			:mask-closable="true"
			:close-on-esc="true"
			class="add-permission-modal"
		>
			<template #header>
				<span class="text-lg font-semibold">{{ $t('Add Permission') }}</span>
			</template>
			<n-space vertical :size="20">
				<n-form-item :label="$t('Select {type}', { type: getTypeLabel(currentDropdownOption.pagetype) })">
					<!-- 这里需要使用 LinkControl 或类似的组件来选择文档 -->
					<n-input
						v-model:value="selectedDocument"
						:placeholder="$t('Select {type}', { type: getTypeLabel(currentDropdownOption.pagetype) })"
						:size="inputSize"
						class="w-full"
						readonly
						@click="showDocumentSelector = true"
					/>
				</n-form-item>
			</n-space>
			<template #action>
				<n-space :vertical="isMobile" :size="isMobile ? 12 : 16" class="w-full">
					<n-button @click="showAddPermissionDialog = false" :block="isMobile" :size="buttonSize">
						{{ $t('Cancel') }}
					</n-button>
					<n-button
						type="primary"
						:loading="addPermissionLoading"
						:disabled="!selectedDocument"
						@click="handleAddPermission"
						:block="isMobile"
						:size="buttonSize"
					>
						{{ $t('Add') }}
					</n-button>
				</n-space>
			</template>
		</n-modal>
	</div>
</template>

<script setup>
import {
	createDocumentResource,
	createResource,
} from 'jingrow-ui';
import { computed, h, ref, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue';
import {
	NCard,
	NButton,
	NDropdown,
	NTooltip,
	NIcon,
	NModal,
	NSpace,
	NFormItem,
	NInput,
} from 'naive-ui';
import ArrowLeftIcon from '~icons/lucide/arrow-left';
import ShieldIcon from '~icons/lucide/shield';
import AppWindowIcon from '~icons/lucide/app-window';
import ChevronDownIcon from '~icons/lucide/chevron-down';
import ObjectList from '../ObjectList.vue';
import { toast } from 'vue-sonner';
import { getToastErrorMessage } from '../../utils/toast';
import { icon, renderDialog } from '../../utils/components';
import RoleConfigureDialog from './RoleConfigureDialog.vue';
import { useRouter } from 'vue-router';

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

let selectedItems = ref(new Set());
const windowWidth = ref(window.innerWidth);
const showAddPermissionDialog = ref(false);
const showDocumentSelector = ref(false);
const selectedDocument = ref('');
const addPermissionLoading = ref(false);
const permissionsResourceRef = ref(null);

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);
});

const props = defineProps({
	roleId: { type: String, required: true },
});

const role = createDocumentResource({
	pagetype: 'Jcloud Role',
	name: props.roleId,
	auto: true,
	whitelistedMethods: {
		addUser: 'add_user',
		removeUser: 'remove_user',
		bulkDelete: 'delete_permissions',
	},
});

const docInsert = createResource({
	url: 'jcloud.api.client.insert',
});

const dropdownOptions = [
	{ label: $t('Allowed Sites'), pagetype: 'Site', fieldname: 'site' },
	{
		label: $t('Allowed Release Groups'),
		pagetype: 'Release Group',
		fieldname: 'release_group',
	},
	{ label: $t('Allowed Servers'), pagetype: 'Server', fieldname: 'server' },
];
const currentDropdownOption = ref(dropdownOptions[0]);
function getDropdownOptions(listResource) {
	return dropdownOptions.map((option) => {
		return {
			label: option.label,
			key: option.pagetype,
		};
	});
}

function handleDropdownSelect(key, listResource) {
	const option = dropdownOptions.find(opt => opt.pagetype === key);
	if (!option) return;
	
	currentDropdownOption.value = option;
	let filters = {
		role: props.roleId,
	};
	if (option.pagetype === 'Site') {
		filters.site = ['is', 'set'];
	}
	if (option.pagetype === 'Release Group') {
		filters.release_group = ['is', 'set'];
	}
	if (option.pagetype === 'Server') {
		filters.server = ['is', 'set'];
	}
	listResource.update({ filters });
	listResource.reload();
}

const rolePermissions = ref({
	pagetype: 'Jcloud Role Permission',
	fields: [
		'site',
		'site.host_name as site_host_name',
		'release_group',
		'release_group.title as release_group_title',
		'server',
		'server.title as server_title',
	],
	filters: {
		role: props.roleId,
		site: ['is', 'set'],
	},
	selectable: true,
	columns: [
		{
			label: computed(() => {
				const pagetype = currentDropdownOption.value.pagetype;
				if (pagetype === 'Release Group') {
					return $t('Release Group');
				}
				if (pagetype === 'Site') {
					return $t('Site');
				}
				if (pagetype === 'Server') {
					return $t('Server');
				}
				return pagetype;
			}),
			format(_value, row) {
				return (
					row.site_host_name ||
					row.site ||
					row.release_group_title ||
					row.server_title
				);
			},
		},
	],
	actions({ listResource: permissions }) {
		return [
			{
				label: $t('Configure'),
				slots: {
					prefix: icon('settings'),
				},
				onClick() {
					renderDialog(h(RoleConfigureDialog, { roleId: props.roleId }));
				},
			},
			{
				label: $t('Delete'),
				slots: {
					prefix: icon('trash-2'),
				},
				condition: () => selectedItems.value.size > 0,
				onClick() {
					role.bulkDelete.submit(
						{
							permissions: Array.from(selectedItems.value),
						},
						{
							onSuccess: () => {
								toast.success($t('Items deleted successfully'));
								selectedItems.value.clear();
							},
						},
					);
				},
			},
			{
				label: $t('Add'),
				slots: {
					prefix: icon('plus'),
				},
				onClick() {
					permissionsResourceRef.value = permissions;
					selectedDocument.value = '';
					showAddPermissionDialog.value = true;
				},
			},
		].filter((action) => (action.condition ? action.condition() : true));
	},
});

function getTypeLabel(pagetype) {
	if (pagetype === 'Release Group') {
		return $t('Release Group');
	}
	if (pagetype === 'Site') {
		return $t('Site');
	}
	if (pagetype === 'Server') {
		return $t('Server');
	}
	return pagetype;
}

async function handleAddPermission() {
	if (!selectedDocument.value || !permissionsResourceRef.value) return;
	if (addPermissionLoading.value) return;
	
	const key = currentDropdownOption.value.fieldname;
	addPermissionLoading.value = true;
	try {
		await toast.promise(
			docInsert.submit({
				pg: {
					pagetype: 'Jcloud Role Permission',
					role: props.roleId,
					[key]: selectedDocument.value,
				},
			}),
			{
				loading: $t('Adding permission...'),
				success() {
					permissionsResourceRef.value.reload();
					showAddPermissionDialog.value = false;
					selectedDocument.value = '';
					return $t('Permission added successfully');
				},
				error: (e) => getToastErrorMessage(e),
			}
		);
	} finally {
		addPermissionLoading.value = false;
	}
}
</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(.add-permission-modal .n-card) {
	width: 700px;
	max-width: 90vw;
}

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

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

:deep(.add-permission-modal .n-input) {
	width: 100%;
}

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

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

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

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

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

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