//
//  InputPhoneNumber.swift
//  Pods
//
//  Created by sophia on 20/10/25.
//

import SwiftUI
public struct InputPhoneNumber: View {
    @Binding public var text: String
    
    public var placeholder: String
    public var size: InputSize
    public var hintText: String
    public var error: String
    public var loading: Bool
    public var rightIcon: String
    public var rightIconColor: Color
    public var autofocus: Bool
    public var onChangeText: ((String) -> Void)?
    public var onFocus: (() -> Void)?
    public var onBlur: (() -> Void)?
    public var onRightIconPressed: (() -> Void)?
    public var accessibilityLabel: String?
    
    @State private var isFocused: Bool = false
    
    public init(
        text: Binding<String>,
        placeholder: String = "0123456789",
        size: InputSize = .small,
        hintText: String = "",
        error: String = "",
        loading: Bool = false,
        required: Bool = false,
        rightIcon: String = "",
        rightIconColor: Color = Colors.black12,
        autofocus: Bool = false,
        onChangeText: ((String) -> Void)? = nil,
        onFocus: (() -> Void)? = nil,
        onBlur: (() -> Void)? = nil,
        onRightIconPressed: (() -> Void)? = nil,
        accessibilityLabel: String? = nil
    ) {
        self._text = text
        self.placeholder = placeholder
        self.size = size
        self.hintText = hintText
        self.error = error
        self.loading = loading
        self.rightIcon = rightIcon
        self.rightIconColor = rightIconColor
        self.autofocus = autofocus
        self.onChangeText = onChangeText
        self.onFocus = onFocus
        self.onBlur = onBlur
        self.onRightIconPressed = onRightIconPressed
        self.accessibilityLabel = accessibilityLabel
    }
    
    // MARK: - Body
    public var body: some View {
        let textBinding = Binding<String>(
            get: { self.text },
            set: { newValue in
                self.text = newValue
                self.onChangeText?(newValue)
            }
        )
        
        VStack(alignment: .leading, spacing: 4) {
            HStack(spacing: 0) {
                // 🇻🇳 Flag
                ImageView("https://static.momocdn.net/app/img/icon/ic-qrcode-package/ic_vn_flag.png")
                    .frame(width: 24, height: 24)
                    .padding(.trailing, Spacing.XS)
                
                MomoText("+84", typography: size == .small ? .headerSSemibold : .headerMBold)
                    .foregroundColor(Colors.black17)
                
                Rectangle()
                    .fill(Colors.black04)
                    .frame(width: 1, height: size == .small ? 24 : 32)
                    .padding(.horizontal, Spacing.M)
                
                // Text input
                ZStack(alignment: .leading) {
                    if text.isEmpty {
                        MomoText(placeholder, typography: size == .small ? .headerSSemibold : .headerMBold, color: Colors.black12)
                    }
                    
                    TextField("", text: textBinding, onEditingChanged: { focused in
                        handleFocusChange(focused)
                    })
                    .keyboardType(.numberPad)
                    .font(size == .small ? .header_s_semibold : .header_m_bold)
                    .foregroundColor(Colors.black17)
                    .applyPrimaryCursorColor()
                    .lineLimit(1)
                    .accessibility(identifier: accessibilityLabel ?? "")
                    .accessibilityValue(textBinding.wrappedValue.isEmpty ? placeholder : textBinding.wrappedValue)
                }
                
                // Clear button
                if isFocused && !text.isEmpty {
                    SwiftUI.Button(action: {
                        text = ""
                        onChangeText?("")
                    }) {
                        Icon(source: "24_navigation_close_circle_full", size: 16, color: Colors.black12)
                            .padding(.leading, Spacing.S).accessibility(identifier: "ic_clear")
                    }
                }
                
                // Loading indicator
                if loading {
                    ActivityIndicator(isAnimating: .constant(true), style: .medium)
                        .frame(width: 16, height: 16)
                }
                
                // ✅ Right icon
                if !rightIcon.isEmpty {
                    SwiftUI.Button(action: { onRightIconPressed?() }) {
                        Icon(source: rightIcon, size: 24, color: rightIconColor)
                            .padding(.leading, Spacing.S)
                    }
                }
            }
            .padding(.horizontal, Spacing.M)
            .frame(height: scaleSize(size == .small ? 48 : 56, 1.1))
            .background(
                RoundedRectangle(cornerRadius: Radius.S)
                    .fill(Colors.black01)
            )
            .overlay(
                RoundedRectangle(cornerRadius: Radius.S)
                    .stroke(borderColor(), lineWidth: isFocused ? 1.5 : 1)
            )
            
            // Error or hint
            ErrorView(
                errorMessage: error,
                errorSpacing: false,
                hintText: hintText
            )
        }
    }
    
    // MARK: - Helpers
    
    private func handleFocusChange(_ focused: Bool) {
        isFocused = focused
        if focused {
            onFocus?()
        } else {
            onBlur?()
        }
    }
    
    private func borderColor() -> Color {
        if !error.isEmpty { return Colors.red03 }
        if isFocused { return Colors.primary }
        return Colors.black04
    }
}

private extension View {
    func applyPrimaryCursorColor() -> some View {
        if #available(iOS 15.0, *) {
            // Modern SwiftUI: use .tint() for cursor
            return self.tint(Colors.primary)
        } else {
            // iOS 13–14: return unchanged (no tint support)
            return self
        }
    }
}

