//
//  SQPhoneField.swift
//  Allovoisins
//
//  Created by Claude on 22/10/2025.
//  Copyright © 2025 AlloVoisins. All rights reserved.
//

import SwiftUI

// MARK: - SQPhoneField

/// Specialized text field for phone number input with automatic formatting.
///
/// Use View Modifiers to configure the phone field:
/// ```swift
/// SQPhoneField("Téléphone", text: $phone)
///     .sqPlaceholder("01 23 45 67 89")
///     .sqHelperText("Format : 01 23 45 67 89")
///     .sqError($phoneError)
/// ```
struct SQPhoneField: View {
    private let label: String
    @Binding var text: String

    @FocusState private var isFocused: Bool
    @Environment(\.sqTextFieldConfiguration) private var config

    private var accentColor: Color { .sqNeutral(80) }

    /// Creates a phone number field with automatic formatting.
    ///
    /// - Parameters:
    ///   - label: The label text displayed above the field
    ///   - text: Binding to the phone number text value
    init(_ label: String, text: Binding<String>) {
        self.label = label
        self._text = text
    }

    var body: some View {
        SQTextFieldBase(label, isFocused: Binding(get: { isFocused }, set: { isFocused = $0 }), textCount: text.count) {
            TextField("", text: $text)
                .placeholder(when: text.isEmpty) {
                    SQText(config.placeholder)
                        .sqColor(.sqNeutral(50))
                }
                .onChange(of: text) { newValue in
                    // Format and limit phone number
                    let formatted = formatPhoneNumber(String(newValue.prefix(15)))
                    if formatted != newValue {
                        text = formatted
                    }
                    // Reset error
                    config.error.wrappedValue = .none
                }
                .keyboardType(.numberPad)
                .foregroundStyle(Color.sqNeutral(100))
                .tint(accentColor)
                .focused($isFocused)
                .accessibilityLabel(label)
                .accessibilityValue(text.isEmpty ? "Vide" : text)
        }
    }

    // MARK: - Helper Methods

    private func formatPhoneNumber(_ number: String) -> String {
        let numbers = number.filter { $0.isNumber }
        var result = ""

        for (index, char) in numbers.enumerated() {
            if index > 0 && index % 2 == 0 {
                result += " "
            }
            result += String(char)
        }

        return result
    }
}

// MARK: - Preview

#Preview {
    VStack(spacing: 32) {
        SQPhoneField("Téléphone", text: .constant(""))
            .sqPlaceholder("01 23 45 67 89")

        SQPhoneField("Téléphone", text: .constant("06 12 34 56 78"))
            .sqPlaceholder("01 23 45 67 89")

        SQPhoneField("Téléphone", text: .constant(""))
            .sqPlaceholder("01 23 45 67 89")
            .sqOptional()

        SQPhoneField("Téléphone", text: .constant(""))
            .sqPlaceholder("01 23 45 67 89")
            .disabled(true)

        SQPhoneField("Téléphone portable", text: .constant(""))
            .sqPlaceholder("01 23 45 67 89")
            .sqHelperText("Format : 01 23 45 67 89")
    }
    .padding()
}
