<template>
	<NcAppNavigationItem menu-placement="top" :name="t('repod', 'Sleep timer')">
		<template #actions>
			<NcActionInput
				v-if="!sleep"
				v-model="input"
				:label="t('repod', 'Minutes')"
				:label-outside="false"
				type="number"
				@submit="setTimer">
				<template #icon>
					<ClockVue :size="20" />
				</template>
			</NcActionInput>
		</template>
		<template #extra>
			<div v-if="sleep" class="extra">
				{{ label }}
				<BellCancel class="pointer" :size="20" @click="stopTimer" />
			</div>
		</template>
		<template #icon>
			<BellSleepIcon v-if="sleep" :size="20" />
			<BellSleepOutlineIcon v-if="!sleep" :size="20" />
		</template>
	</NcAppNavigationItem>
</template>

<script lang="ts">
import { NcActionInput, NcAppNavigationItem } from '@nextcloud/vue'
import { n, t } from '@nextcloud/l10n'
import BellCancel from 'vue-material-design-icons/BellCancel.vue'
import BellSleepIcon from 'vue-material-design-icons/BellSleep.vue'
import BellSleepOutlineIcon from 'vue-material-design-icons/BellSleepOutline.vue'
import ClockVue from 'vue-material-design-icons/Clock.vue'
import { mapActions } from 'pinia'
import { usePlayer } from '../../store/player.ts'

export default {
	name: 'Sleep',
	components: {
		BellCancel,
		BellSleepIcon,
		BellSleepOutlineIcon,
		ClockVue,
		NcActionInput,
		NcAppNavigationItem,
	},
	data: () => ({
		input: 10,
		sleep: null as NodeJS.Timeout | null,
		timer: 0,
	}),
	computed: {
		label() {
			if (this.timer > 60) {
				return this.n(
					'repod',
					'%n min',
					'%n mins',
					Math.round(this.timer / 60),
				)
			} else {
				return this.n('repod', '%n sec', '%n secs', this.timer)
			}
		},
	},
	methods: {
		...mapActions(usePlayer, ['stop']),
		n,
		t,
		setTimer() {
			this.timer = this.input * 60
			this.sleep = setInterval(() => {
				if (this.timer > 0) {
					this.timer--
				} else if (this.sleep) {
					this.stopTimer()
					this.stop()
				}
			}, 1000)
		},
		stopTimer() {
			if (this.sleep) {
				clearTimeout(this.sleep)
				this.sleep = null
			}
		},
	},
}
</script>

<style scoped>
.extra {
	align-items: center;
	display: flex;
	gap: 0.5rem;
}

.pointer {
	cursor: pointer;
}
</style>
