import { parsePhoneNumberFromString } from 'libphonenumber-js/max'

export function useInternationalPhone(defaultCountryCode = '+995') {
  const phoneCountryCode = ref(sanitizePhoneCountryCode(defaultCountryCode))
  const phoneNumber = ref('')

  function sanitizePhoneCountryCode(value) {
    const digitsOnly = String(value || '').replace(/\D/g, '').slice(0, 4)
    return digitsOnly ? `+${digitsOnly}` : '+'
  }

  function sanitizePhoneNumber(value) {
    return String(value || '')
      .replace(/[^\d\s()+-]/g, '')
      .replace(/\s{2,}/g, ' ')
      .trimStart()
  }

  function parseInternationalPhone(countryCode = phoneCountryCode.value, phone = phoneNumber.value) {
    const normalizedCountryCode = sanitizePhoneCountryCode(countryCode)
    const normalizedPhone = sanitizePhoneNumber(phone)

    if (normalizedCountryCode === '+' || !normalizedPhone) {
      return null
    }

    return parsePhoneNumberFromString(`${normalizedCountryCode} ${normalizedPhone}`)
  }

  const phoneValidationState = computed(() => {
    if (!phoneNumber.value.replace(/\D/g, '')) {
      return { valid: false, message: '', number: '' }
    }

    const parsedPhone = parseInternationalPhone()

    if (parsedPhone?.isValid()) {
      return { valid: true, message: '', number: parsedPhone.number }
    }

    return { valid: false, message: '', number: '' }
  })

  const isPhoneValid = computed(() => phoneValidationState.value.valid)

  function handlePhoneChange(event) {
    phoneNumber.value = sanitizePhoneNumber(event.target.value)
  }

  function handlePhoneCountryCodeChange(event) {
    phoneCountryCode.value = sanitizePhoneCountryCode(event.target.value)
  }

  function combinePhone() {
    return phoneValidationState.value.number || `${sanitizePhoneCountryCode(phoneCountryCode.value)} ${sanitizePhoneNumber(phoneNumber.value)}`.trim()
  }

  function resetPhone() {
    phoneCountryCode.value = sanitizePhoneCountryCode(defaultCountryCode)
    phoneNumber.value = ''
  }

  return {
    combinePhone,
    handlePhoneChange,
    handlePhoneCountryCodeChange,
    isPhoneValid,
    phoneCountryCode,
    phoneDigits: computed(() => phoneNumber.value.replace(/\D/g, '')),
    phoneNumber,
    phoneValidationState,
    resetPhone,
    sanitizePhoneCountryCode,
    sanitizePhoneNumber,
  }
}
