<script lang="ts" setup>
import { onMounted, ref } from 'vue'

import { useAuthStore } from '@/stores/auth'
import { getProviderList, type HydratedProvider } from '@/utils/pds'

import Button from '../../UI/BaseButton.vue'
import Modal from '../../UI/BaseModal.vue'
import TextInput from '@/components/UI/TextInput.vue'

const auth = useAuthStore()

const providers = ref<HydratedProvider[]>([])
const selectedProvider = ref<HydratedProvider>()

const pdsError = ref('')
const pdsInput = ref('')

async function submitPds() {
	const val =
		pdsInput.value.trim() === '' ? selectedProvider.value?.url.toString() : pdsInput.value.trim()
	if (!val) {
		pdsError.value = 'Enter a PDS URL or handle'
		return
	}
	await auth.login(val)
}

onMounted(async () => {
	providers.value = await getProviderList()
	if (providers.value.length) {
		selectedProvider.value = providers.value[0]
	} else {
		pdsError.value = 'No providers available'
	}
})
</script>

<template>
	<Modal title="Enter your handle" @close="$emit('close')" width="480px">
		<div class="modal-body">
			<label for="pds-input" class="sr-only">PDS URL or handle</label>

			<TextInput
				id="pds-input"
				v-model="pdsInput"
				placeholder="https://pds.example or example.cat"
				:error="pdsError"
				inputmode="url"
				aria-describedby="pds-error"
				@keydown.enter.prevent="submitPds"
				style="margin-top: 1rem"
			/>

			<div id="pds-error" role="alert" v-if="pdsError">{{ pdsError }}</div>
		</div>

		<template #footer>
			<Button variant="ghost" type="button" @click="$emit('close')">Cancel</Button>
			<Button variant="primary" :loading="auth.isLoading" @click="submitPds" type="button">
				Sign in
			</Button>
		</template>
	</Modal>
</template>
