<template>
	<div class="phone-input">
		<NcTextField :model-value="modelValue"
			:disabled="disabled"
			:placeholder="'+49 176 12345678'"
			@update:model-value="onInput" />
		<div class="phone-input__feedback">
			<span v-if="validationState === 'valid'" class="phone-input__valid">
				Gültig ({{ formattedNumber }})
			</span>
			<span v-else-if="validationState === 'invalid'" class="phone-input__invalid">
				{{ validationMessage }}
			</span>
			<span v-else class="phone-input__hint">
				Format: +49 176 12345678
			</span>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { NcTextField } from '@nextcloud/vue'

const props = defineProps({
	modelValue: {
		type: String,
		default: '',
	},
	disabled: {
		type: Boolean,
		default: false,
	},
})

const emit = defineEmits(['update:modelValue'])

const validationState = ref('hint') // 'hint' | 'valid' | 'invalid'
const validationMessage = ref('')
const formattedNumber = ref('')

/**
 * Clean a phone number string (strip formatting characters).
 */
function clean(number) {
	return number.replace(/[\s\-\(\)\/\.]/g, '').trim()
}

/**
 * Normalize a phone number to E.164 format.
 */
function normalize(number) {
	const cleaned = clean(number)

	if (cleaned.startsWith('+')) {
		return cleaned
	}
	if (cleaned.startsWith('00')) {
		return '+' + cleaned.substring(2)
	}
	if (cleaned.startsWith('0')) {
		return '+49' + cleaned.substring(1)
	}
	return '+' + cleaned
}

/**
 * Validate E.164 format: + followed by 1-15 digits.
 */
function isValidE164(number) {
	return /^\+[1-9][0-9]{1,14}$/.test(number)
}

/**
 * Format a normalized E.164 number for display.
 */
function formatForDisplay(normalized) {
	if (normalized.startsWith('+49') && normalized.length >= 12) {
		// German number: +49 XXX XXXXXXX
		const rest = normalized.substring(3)
		if (rest.length >= 4) {
			return '+49 ' + rest.substring(0, 3) + ' ' + rest.substring(3)
		}
	}
	return normalized
}

function onInput(value) {
	emit('update:modelValue', value)
	validate(value)
}

function validate(value) {
	if (!value || value.trim() === '') {
		validationState.value = 'hint'
		validationMessage.value = ''
		formattedNumber.value = ''
		return
	}

	const cleaned = clean(value)
	if (cleaned.length < 3) {
		validationState.value = 'hint'
		return
	}

	const normalized = normalize(value)

	if (isValidE164(normalized)) {
		validationState.value = 'valid'
		formattedNumber.value = formatForDisplay(normalized)
	} else {
		validationState.value = 'invalid'
		const digits = normalized.substring(1)

		if (!/^[0-9]*$/.test(digits)) {
			validationMessage.value = 'Nur Ziffern nach dem + erlaubt'
		} else if (digits.length < 2) {
			validationMessage.value = 'Nummer zu kurz'
		} else if (digits.length > 15) {
			validationMessage.value = 'Nummer zu lang (max. 15 Ziffern)'
		} else {
			validationMessage.value = 'Ungültiges Format'
		}
	}
}

// Validate on initial value
watch(() => props.modelValue, (val) => {
	if (val) {
		validate(val)
	}
}, { immediate: true })
</script>

<style scoped>
.phone-input__feedback {
	margin-top: 4px;
	font-size: 0.85em;
	min-height: 1.2em;
}

.phone-input__valid {
	color: var(--color-success);
}

.phone-input__invalid {
	color: var(--color-error);
}

.phone-input__hint {
	color: var(--color-text-lighter);
}
</style>
