import {
  AsYouType,
  CountryCode,
  getCountries,
  getCountryCallingCode,
  isValidPhoneNumber,
  parsePhoneNumberFromString,
} from "libphonenumber-js"

export const DEFAULT_COUNTRY: CountryCode = "IR"

export function toLatinDigits(value: string): string {
  return value
    .replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06f0))
    .replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660))
}

/** What the learner typed or pasted, as a country and the digits they see. */
export function readPhoneInput(raw: string, country: CountryCode): { country: CountryCode; national: string } {
  const text = toLatinDigits(raw).trim()
  const international = text.startsWith("+") ? text : text.startsWith("00") ? `+${text.slice(2)}` : null

  if (international) {
    const parsed = parsePhoneNumberFromString(international)
    if (parsed?.country) return { country: parsed.country, national: String(parsed.nationalNumber) }
  }

  let digits = text.replace(/\D/g, "")
  if (country === "IR" && digits.startsWith("98") && digits.length >= 12) digits = digits.slice(2)

  return { country, national: digits.slice(0, country === "IR" ? 11 : 15) }
}

/** The number without its trunk 0: 09123456789 → 9123456789. */
export function nationalNumber(national: string, country: CountryCode): string {
  return country === "IR" ? national.replace(/^0+/, "") : national
}

/** null when it can receive our SMS; otherwise the reason, for the field's message. */
export function phoneError(typed: string, country: CountryCode): string | null {
  const national = nationalNumber(typed, country)
  if (typed === "") return "شماره موبایلت را وارد کن."

  if (country === "IR") {
    if (!national.startsWith("9")) return "شماره موبایل ایران با ۰۹ شروع می‌شود."
    if (national.length !== 10) return "شماره موبایل ۱۱ رقم است (با صفر اول)."
    return null
  }

  return isValidPhoneNumber(national, country) ? null : "این شماره برای کشور انتخاب‌شده معتبر نیست."
}

/** +989123456789, the form the server stores and sends SMS to. */
export function toE164(typed: string, country: CountryCode): string | null {
  return parsePhoneNumberFromString(nationalNumber(typed, country), country)?.number ?? null
}

export function formatNational(typed: string, country: CountryCode): string {
  if (country === "IR") {
    const lead = typed.startsWith("0") ? 4 : 3
    return [typed.slice(0, lead), typed.slice(lead, lead + 3), typed.slice(lead + 3)].filter(Boolean).join(" ")
  }
  return new AsYouType(country).input(typed)
}

export function formatInternational(e164: string): string {
  return parsePhoneNumberFromString(e164)?.formatInternational() ?? e164
}

export function callingCode(country: CountryCode): string {
  return `+${getCountryCallingCode(country)}`
}


export type CountryOption = { code: CountryCode; name: string; dial: string }

let cachedCountries: CountryOption[] | null = null

/** Every country with its Persian name where the WebView knows it; Iran first. */
export function countryOptions(): CountryOption[] {
  if (cachedCountries) return cachedCountries

  let names: { of(code: string): string | undefined } | null = null
  try {
    // Intl.DisplayNames needs Chrome 81+; older WebViews fall back to the ISO code.
    const DisplayNames = (Intl as unknown as { DisplayNames?: new (l: string[], o: { type: string }) => { of(c: string): string | undefined } }).DisplayNames
    names = DisplayNames ? new DisplayNames(["fa"], { type: "region" }) : null
  } catch {
    names = null
  }

  const all = getCountries().map((code) => ({ code, name: names?.of(code) ?? code, dial: callingCode(code) }))
  all.sort((a, b) => (a.code === DEFAULT_COUNTRY ? -1 : b.code === DEFAULT_COUNTRY ? 1 : a.name.localeCompare(b.name, "fa")))
  cachedCountries = all
  return all
}
