<template>
	<div>
		<header
			class="sticky top-0 z-10 flex items-center justify-between border-b bg-white px-5 py-2.5"
		>
			<Breadcrumbs
				:items="[{ label: $t('Notifications'), route: { name: 'Notifications' } }]"
			>
				<template #actions>
					<TabButtons
						:buttons="tabButtons"
						v-model="activeTab"
					/>
				</template>
			</Breadcrumbs>
		</header>

		<div class="mx-20 mt-5">
			<div class="flex flex-col divide-y">
				<ListItem
					v-for="notification in notifications"
					:title="notification.type"
					:description="`${notification.message} • ${formatDate(
						notification.creation,
						'relative'
					)}`"
				>
					<template #actions>
						<Button
							v-if="notification.route"
							variant="ghost"
							:label="$t('View')"
							@click="openNotification(notification)"
						/>
					</template>
				</ListItem>
				<div v-if="!notifications?.length" class="text-base text-gray-600">
					{{ $t('No Notifications') }}
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { TabButtons } from 'jingrow-ui';
import { unreadNotificationsCount } from '@/data/notifications';

export default {
	name: 'Notifications',
	pageMeta() {
		return {
			title: this.$t('Notifications')
		};
	},
	components: {
		TabButtons
	},
	data() {
		return {
			activeTab: null
		};
	},
	computed: {
		tabButtons() {
			return [
				{ label: this.$t('Unread'), active: true },
				{ label: this.$t('Read') }
			];
		},
		notifications() {
			return this.activeTab === this.$t('Unread')
				? this.$resources.unreadNotifications.data
				: this.$resources.readNotifications.data;
		}
	},
	mounted() {
		// 初始化 activeTab 为第一个按钮的 label
		if (!this.activeTab) {
			this.activeTab = this.tabButtons[0].label;
		}
	},
	resources: {
		unreadNotifications() {
			if (this.activeTab !== this.$t('Unread')) return;
			return {
				url: 'jcloud.api.notifications.get_notifications',
				params: {
					filters: { team: this.$account.team.name, read: false }
				},
				cache: ['unreadNotifications', this.$account?.team],
				auto: true
			};
		},
		readNotifications() {
			if (this.activeTab !== this.$t('Read')) return;
			return {
				url: 'jcloud.api.notifications.get_notifications',
				params: {
					filters: {
						team: this.$account.team.name,
						read: true
					}
				},
				cache: ['readNotifications', this.$account?.team],
				auto: true
			};
		},
		markNotificationAsRead: {
			url: 'jcloud.api.notifications.mark_notification_as_read'
		}
	},
	methods: {
		openNotification(notification) {
			if (!notification.read) {
				this.$resources.markNotificationAsRead.submit({
					name: notification.name
				});

				unreadNotificationsCount.setData(data => data - 1);
			}
			this.$router.push(notification.route);
		}
	}
};
</script>
