<template>
	<MkStickyContainer>
		<template #header><MkPageHeader :actions="headerActions" /></template>
		<div class="mk-group-page">
			<div class="_section members _gap">
				<div class="_content settings" v-if="group">
					<div class="_monospace" v-if="group.username">
						Public page:
						<MkA :to="`/@@${group.username}`" class="_link"
							>@@{{ group.username }}</MkA
						>
					</div>
					<div v-else>
						Set a group username from the header menu to enable a public group page.
					</div>
					<div class="emoji-form">
						<MkInput v-model="emojiName" pattern="^[a-z0-9_]{1,64}$">
							<template #label>Group emoji/glyph name</template>
						</MkInput>
						<MkSwitch v-model="emojiGlyph">
							<template #label>Glyph</template>
						</MkSwitch>
						<MkButton inline @click="addEmoji">
							<i class="ph-image-square ph-bold ph-lg"></i>
							Add
						</MkButton>
					</div>
					<div class="emojis">
						<div v-for="emoji in emojis" :key="emoji.id" class="emoji _panel">
							<img :src="emoji.url" :alt="emoji.name" />
							<div class="_monospace">
								{{ emoji.glyph ? `;${emoji.name}@@${group.username ?? "group"};` : `:${emoji.name}@@${group.username ?? "group"}:` }}
							</div>
							<button class="_button" @click="deleteEmoji(emoji)">
								<i class="ph-trash ph-bold ph-lg"></i>
							</button>
						</div>
					</div>
				</div>
				<div class="_content">
					<div class="users">
						<div
							v-for="user in users"
							:key="user.id"
							class="user _panel"
						>
							<MkAvatar
								:user="user"
								class="avatar"
								:show-indicator="true"
							/>
							<div class="body">
								<MkUserName :user="user" class="name" />
								<MkAcct :user="user" class="acct" />
							</div>
							<div class="action">
								<button
									class="_button"
									@click="removeUser(user)"
									:aria-label="i18n.t('removeMember')"
								>
									<i class="ph-x ph-bold ph-lg"></i>
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</MkStickyContainer>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from "vue";
import { definePageMetadata } from "@/scripts/page-metadata";
import { i18n } from "@/i18n";
import { useRouter } from "@/router";
import * as os from "@/os";
import MkInput from "@/components/form/input.vue";
import MkSwitch from "@/components/form/switch.vue";
import MkButton from "@/components/MkButton.vue";
import { selectFile } from "@/scripts/select-file";

const props = defineProps<{
	groupId: {
		type: string;
		required: true;
	};
}>();

const users = ref<any[]>([]);
const group = ref<any>();
const emojis = ref<any[]>([]);
const emojiName = ref("");
const emojiGlyph = ref(false);

const router = useRouter();

watch(
	() => props.groupId,
	() => {
		fetch();
	},
);

async function fetch() {
	os.api("users/groups/show", {
		groupId: props.groupId,
	}).then((gp) => {
		group.value = gp;
		loadEmojis();
		os.api("users/show", {
			userIds: group.value.userIds,
		}).then((us) => {
			users.value = us;
		});
	});
}

fetch();

function invite() {
	os.selectLocalUser().then((user) => {
		os.apiWithDialog("users/groups/invite", {
			groupId: group.value.id,
			userId: user.id,
		});
	});
}

function removeUser(user) {
	os.api("users/groups/pull", {
		groupId: group.value.id,
		userId: user.id,
	}).then(() => {
		users.value = users.value.filter((x) => x.id !== user.id);
	});
}

async function renameGroup() {
	const { canceled, result: name } = await os.inputText({
		title: i18n.ts.groupName,
		default: group.value.name,
	});
	if (canceled) return;

	await os.api("users/groups/update", {
		groupId: group.value.id,
		name: name,
	});

	group.value.name = name;
}

async function loadEmojis() {
	if (!group.value) return;
	emojis.value = await os.api("users/groups/emojis/list", {
		groupId: group.value.id,
	});
}

async function addEmoji(ev: MouseEvent) {
	const name = emojiName.value.trim();
	if (!/^[a-z0-9_]{1,64}$/.test(name)) return;
	const file = await selectFile(ev.currentTarget ?? ev.target, "Group emoji image");
	await os.apiWithDialog("users/groups/emojis/create", {
		groupId: group.value.id,
		name,
		fileId: file.id,
		glyph: emojiGlyph.value,
	});
	emojiName.value = "";
	await loadEmojis();
}

async function deleteEmoji(emoji) {
	await os.apiWithDialog("users/groups/emojis/delete", { id: emoji.id });
	await loadEmojis();
}

async function setUsername() {
	const { canceled, result: username } = await os.inputText({
		title: "Group username",
		default: group.value.username ?? "",
	});
	if (canceled) return;

	await os.api("users/groups/update", {
		groupId: group.value.id,
		name: group.value.name,
		username: username ? username.trim() : null,
	});

	group.value.username = username ? username.trim().toLowerCase() : null;
}

async function toggleCalls() {
	const allowCalls = !group.value.allowCalls;
	await os.api("users/groups/update", {
		groupId: group.value.id,
		name: group.value.name,
		allowCalls,
	});
	group.value.allowCalls = allowCalls;
}

async function setIcon(ev: MouseEvent) {
	const file = await selectFile(ev.currentTarget ?? ev.target, "Group icon image");
	await os.apiWithDialog("users/groups/update", {
		groupId: group.value.id,
		name: group.value.name,
		iconFileId: file.id,
	});
	await fetch();
}

async function setSymbol(ev: MouseEvent) {
	const file = await selectFile(ev.currentTarget ?? ev.target, "Group symbol image");
	await os.apiWithDialog("users/groups/update", {
		groupId: group.value.id,
		name: group.value.name,
		symbolFileId: file.id,
	});
	await fetch();
}

function transfer() {
	os.selectLocalUser().then((user) => {
		os.apiWithDialog("users/groups/transfer", {
			groupId: group.value.id,
			userId: user.id,
		});
	});
}

async function deleteGroup() {
	const { canceled } = await os.confirm({
		type: "warning",
		text: i18n.t("removeAreYouSure", { x: group.value.name }),
	});
	if (canceled) return;

	await os.apiWithDialog("users/groups/delete", {
		groupId: group.value.id,
	});
	router.push("/my/groups");
}

definePageMetadata(
	computed(() => ({
		title: i18n.ts.members,
		icon: "ph-users-three ph-bold ph-lg",
	})),
);

const headerActions = computed(() => [
	{
		icon: "ph-plus ph-bold ph-lg",
		text: i18n.ts.invite,
		handler: invite,
	},
	{
		icon: "ph-cursor-text ph-bold ph-lg",
		text: i18n.ts.rename,
		handler: renameGroup,
	},
	{
		icon: "ph-at ph-bold ph-lg",
		text: "Username",
		handler: setUsername,
	},
	{
		icon: "ph-image-square ph-bold ph-lg",
		text: "Icon",
		handler: setIcon,
	},
	{
		icon: "ph-identification-badge ph-bold ph-lg",
		text: "Symbol",
		handler: setSymbol,
	},
	{
		icon: group.value?.allowCalls ? "ph-phone-slash ph-bold ph-lg" : "ph-phone ph-bold ph-lg",
		text: group.value?.allowCalls ? "Disable calls" : "Enable calls",
		handler: toggleCalls,
	},
	{
		icon: "ph-arrows-left-right ph-bold ph-lg",
		text: i18n.ts.transfer,
		handler: transfer,
	},
	{
		icon: "ph-trash ph-bold ph-lg",
		text: i18n.ts.delete,
		handler: deleteGroup,
	},
]);
</script>

<style lang="scss" scoped>
.mk-group-page {
	> .members {
		> ._content {
			&.settings {
				padding: 16px;
			}

			.emoji-form {
				display: flex;
				gap: 8px;
				align-items: end;
				flex-wrap: wrap;
				margin-top: 12px;
			}

			.emojis {
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
				gap: 8px;
				margin-top: 12px;
			}

			.emoji {
				display: grid;
				grid-template-columns: 38px minmax(0, 1fr) 32px;
				gap: 8px;
				align-items: center;
				padding: 8px;

				> img {
					width: 38px;
					height: 38px;
					object-fit: contain;
				}
			}

			> .users {
				> ._panel {
					margin: 1rem 2rem;
				}
				> .user {
					display: flex;
					align-items: center;
					padding: 16px;

					> .avatar {
						width: 50px;
						height: 50px;
					}

					> .body {
						flex: 1;
						padding: 8px;

						> .name {
							display: block;
							font-weight: bold;
						}

						> .acct {
							opacity: 0.5;
						}
					}
				}
			}
		}
	}
}
</style>
