<template>
	<div class="team-settings-container">
		<n-card :title="$t('Team Members')" class="settings-card">
			<ObjectList :options="teamMembersListOptions" />
		</n-card>

		<!-- 团队设置弹窗 -->
		<n-modal
			v-model:show="showTeamSettingsDialog"
			preset="card"
			:title="$t('Settings')"
			:style="modalStyle"
			:mask-closable="true"
			:close-on-esc="true"
			class="team-settings-modal"
		>
			<template #header>
				<span class="text-lg font-semibold">{{ $t('Settings') }}</span>
			</template>
			<n-space vertical :size="20">
				<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('Enforce Two-Factor Authentication') }}
							</div>
							<div class="text-sm text-gray-600">
								{{ $t('Require all team members to enable two-factor authentication') }}
							</div>
						</div>
						<n-switch
							:value="enforce2FA"
							@update:value="handleEnforce2FAChange"
							size="medium"
						/>
					</div>
				</n-form-item>
			</n-space>
		</n-modal>

		<!-- 邀请成员弹窗 -->
		<InviteTeamMemberDialog
			v-if="showInviteMemberDialog"
			v-model="showInviteMemberDialog"
			@success="handleInviteSuccess"
		/>

		<!-- 移除成员确认弹窗 -->
		<n-modal
			v-model:show="showRemoveMemberDialog"
			preset="dialog"
			:title="$t('Remove Member')"
			:positive-text="$t('Remove')"
			:positive-button-props="{ type: 'error' }"
			:loading="team.removeTeamMember.loading"
			:mask-closable="true"
			:close-on-esc="true"
			@positive-click="handleRemoveMember"
		>
			<div class="py-4">
				<p class="text-base">
					{{ $t('Are you sure you want to remove') }} <strong>{{ selectedMember?.full_name || '' }}</strong> {{ $t('from the team?') }}
				</p>
			</div>
		</n-modal>
	</div>
</template>

<script setup>
import {
	NCard,
	NModal,
	NSpace,
	NFormItem,
	NSwitch,
	NButton,
} from 'naive-ui';
import { defineAsyncComponent, h, ref, getCurrentInstance, computed, onMounted } from 'vue';
import { toast } from 'vue-sonner';
import { getTeam } from '../../data/team';
import { icon } from '../../utils/components';
import ObjectList from '../ObjectList.vue';
import UserWithAvatarCell from '../UserWithAvatarCell.vue';
import InviteTeamMemberDialog from './InviteTeamMemberDialog.vue';

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

const team = getTeam();
const windowWidth = ref(window.innerWidth);
const showTeamSettingsDialog = ref(false);
const showInviteMemberDialog = ref(false);
const showRemoveMemberDialog = ref(false);
const selectedMember = ref(null);

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

const enforce2FA = computed(() => {
	return Boolean(team.pg?.enforce_2fa);
});

function handleEnforce2FAChange(value) {
	team.setValue.submit({ enforce_2fa: value });
}

function handleInviteSuccess() {
	showInviteMemberDialog.value = false;
	team.getTeamMembers.submit();
}

function handleRemoveMember() {
	if (!selectedMember.value) return;
	team.removeTeamMember.submit({ member: selectedMember.value.name });
	toast.success($t('Member removed'), { duration: 2000 });
	setTimeout(() => {
		team.getTeamMembers.submit();
		showRemoveMemberDialog.value = false;
		selectedMember.value = null;
	}, 500);
}

const teamMembersListOptions = ref({
	onRowClick: () => {},
	rowHeight: 50,
	list: team.getTeamMembers,
	columns: [
		{
			label: $t('User'),
			type: 'Component',
			component: ({ row }) => {
				return h(UserWithAvatarCell, {
					avatarImage: row.user_image,
					fullName: row.full_name,
					email: row.email
				});
			},
			width: 1
		}
	],
	rowActions({ row }) {
		if (row.name === team.pg.user || row.name === team.pg.user_info?.name)
			return [];
		return [
			{
				label: $t('Remove Member'),
				condition: () => row.name !== team.pg.user,
				onClick() {
					selectedMember.value = row;
					showRemoveMemberDialog.value = true;
				}
			}
		];
	},
	secondaryAction() {
		return {
			label: $t('Settings'),
			icon: 'settings',
			onClick: () => {
				showTeamSettingsDialog.value = true;
			}
		};
	},
	primaryAction() {
		return {
			label: $t('Add Member'),
			slots: { prefix: icon('plus') },
			onClick: () => {
				showInviteMemberDialog.value = true;
			}
		};
	}
});

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

onMounted(() => {
	handleResize();
	window.addEventListener('resize', handleResize);
	team.getTeamMembers.submit();
});
</script>

<style scoped>
.team-settings-container {
	width: 100%;
	padding: 24px;
}

.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(.team-settings-modal .n-card) {
	width: 700px;
	max-width: 90vw;
}

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

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

@media (max-width: 768px) {
	.team-settings-container {
		padding: 16px;
	}

	.settings-card {
		border-radius: 8px;
	}

	:deep(.team-settings-modal .n-card) {
		width: 95vw !important;
		max-width: 95vw !important;
		margin: 20px auto;
		border-radius: 12px;
	}

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

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

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

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