package pl.firmatpp.kierowca.ui

import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation

object PolishPhoneNumberVisualTransformation : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        val rawDigits = text.text.filter(Char::isDigit).take(9)
        val formatted = rawDigits.chunked(3).joinToString(" ")

        return TransformedText(
            AnnotatedString(formatted),
            object : OffsetMapping {
                override fun originalToTransformed(offset: Int): Int {
                    val safeOffset = offset.coerceIn(0, rawDigits.length)
                    val spacesBeforeOffset = when {
                        safeOffset <= 3 -> 0
                        safeOffset <= 6 -> 1
                        else -> 2
                    }

                    return (safeOffset + spacesBeforeOffset).coerceAtMost(formatted.length)
                }

                override fun transformedToOriginal(offset: Int): Int {
                    val safeOffset = offset.coerceIn(0, formatted.length)

                    return formatted
                        .take(safeOffset)
                        .count(Char::isDigit)
                        .coerceAtMost(rawDigits.length)
                }
            },
        )
    }
}
