<template>
	<div>
		<Loading v-if="loading" />
		<ul v-if="!loading">
			<NcListItem
				v-for="feed in feeds"
				:key="feed.link"
				:details="formatLocaleDate(new Date(feed.fetchedAtUnix * 1000))"
				:name="feed.title"
				:to="toFeedUrl(feed.link)">
				<template #icon>
					<NcAvatar
						:display-name="feed.author"
						:is-no-user="true"
						:url="feed.imageUrl" />
				</template>
				<template #subname>
					{{ feed.author }}
				</template>
				<template #actions>
					<NcActionButton
						v-if="!getSubByUrl(feed.link)"
						:aria-label="t('repod', 'Subscribe')"
						:name="t('repod', 'Subscribe')"
						:title="t('repod', 'Subscribe')"
						@click="addSubscription(feed.link)">
						<template #icon>
							<PlusIcon :size="20" />
						</template>
					</NcActionButton>
				</template>
			</NcListItem>
		</ul>
	</div>
</template>

<script lang="ts">
import { NcActionButton, NcAvatar, NcListItem } from '@nextcloud/vue'
import { mapActions, mapState } from 'pinia'
import Loading from '../Atoms/Loading.vue'
import PlusIcon from 'vue-material-design-icons/Plus.vue'
import type { PodcastDataInterface } from '../../utils/types.ts'
import axios from '@nextcloud/axios'
import { formatLocaleDate } from '../../utils/time.ts'
import { generateUrl } from '@nextcloud/router'
import { showError } from '../../utils/toast.ts'
import { t } from '@nextcloud/l10n'
import { toFeedUrl } from '../../utils/url.ts'
import { useSubscriptions } from '../../store/subscriptions.ts'

export default {
	name: 'Search',
	components: {
		Loading,
		NcActionButton,
		NcAvatar,
		NcListItem,
		PlusIcon,
	},
	props: {
		value: {
			type: String,
			required: true,
		},
	},
	data: () => ({
		feeds: [] as PodcastDataInterface[],
		loading: false,
		timeout: null as NodeJS.Timeout | null,
	}),
	computed: {
		...mapState(useSubscriptions, ['getSubByUrl']),
	},
	watch: {
		value() {
			if (this.timeout) {
				clearTimeout(this.timeout)
			}
			this.timeout = setTimeout(this.search, 200)
		},
	},
	methods: {
		...mapActions(useSubscriptions, ['fetch']),
		formatLocaleDate,
		t,
		toFeedUrl,
		async addSubscription(url: string) {
			try {
				await axios.post(
					generateUrl('/apps/gpoddersync/subscription_change/create'),
					{
						add: [url],
						remove: [],
					},
				)
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Error while adding the feed'))
			}
			this.fetch()
		},
		async search() {
			try {
				this.loading = true
				const currentSearch = this.value
				const feeds = await axios.get<PodcastDataInterface[]>(
					generateUrl('/apps/repod/search?q={value}', {
						value: currentSearch,
					}),
				)
				if (currentSearch === this.value) {
					this.feeds = [...feeds.data].sort(
						(a: PodcastDataInterface, b: PodcastDataInterface) =>
							b.fetchedAtUnix - a.fetchedAtUnix,
					)
				}
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Could not fetch search results'))
			} finally {
				if (this.feeds) {
					this.loading = false
				}
			}
		},
	},
}
</script>
