//
//  SQTextField.swift
//  Sequoia
//
//  Created by Victor on 10/10/2024.
//

import Lottie
import SwiftUI

// MARK: - SQTextField

/// Standard text field component with optional icon.
///
/// Use View Modifiers to configure the text field:
/// ```swift
/// SQTextField("Name", text: $name)
///     .sqPlaceholder("Enter your name")
///     .sqMinCharacters(2)
///     .sqMaxCharacters(50)
///     .sqError($nameError)
/// ```
struct SQTextField: View {
    private let label: String
    @Binding var text: String
    private let icon: SQIcon?
    private let iconAction: (() -> Void)?

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

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

    /// Creates a standard text field.
    ///
    /// - Parameters:
    ///   - label: The label text displayed above the field
    ///   - text: Binding to the text value
    init(_ label: String, text: Binding<String>, icon: SQIcon? = nil, iconAction: (() -> Void)? = nil) {
        self.label = label
        self._text = text
        self.icon = icon
        self.iconAction = iconAction
    }

    var body: some View {
        SQTextFieldBase(label, isFocused: Binding(get: { isFocused }, set: { isFocused = $0 }), textCount: text.count) {
            HStack(spacing: 4) {
                TextField("", text: $text)
                    .placeholder(when: text.isEmpty) {
                        SQText(config.placeholder)
                            .sqColor(.sqNeutral(50))
                    }
                    .onChange(of: text) { newValue in
                        // Character limit
                        if let max = config.maxCharacters, newValue.count > max {
                            text = String(newValue.prefix(max))
                        }
                        // Reset error
                        config.error.wrappedValue = .none
                    }
                    .keyboardType(config.keyboardType)
                    .foregroundStyle(Color.sqNeutral(100))
                    .tint(accentColor)
                    .submitLabel(.done)
                    .focused($isFocused)
                    .toolbar {
                        ToolbarItemGroup(placement: .keyboard) {
                            if config.keyboardType == .numberPad || config.keyboardType == .decimalPad || config.keyboardType == .phonePad {
                                Spacer()
                                Button("Done") {
                                    isFocused = false
                                }
                            }
                        }
                    }
                    .accessibilityLabel(label)
                    .accessibilityValue(text.isEmpty ? "Vide" : text)

                if config.isLoading.wrappedValue {
                    LottieView(animation: .named("av_loader"))
                        .looping()
                        .frame(width: 20, height: 20)
                } else if let icon = icon {
                    Button(action: iconAction ?? {}) {
                        icon
                    }
                }
            }
        }
    }
}

// MARK: - Icon Modifier

extension SQTextField {
    /// Adds an icon button on the right side of the text field.
    ///
    /// - Parameters:
    ///   - icon: The icon to display
    ///   - action: Action to perform when the icon is tapped
    /// - Returns: A text field with the icon
    func sqIcon(_ icon: SQIcon, action: @escaping () -> Void = {}) -> SQTextField {
        SQTextField(label, text: $text, icon: icon, iconAction: action)
    }
}

// MARK: - Preview

#Preview {
    VStack(spacing: 32) {
        SQTextField("Label name", text: .constant("Bonjour"))
            .sqPlaceholder("Placeholder")
            .sqMinCharacters(20)

        SQTextField("Label name", text: .constant(""))
            .sqPlaceholder("Placeholder")
            .sqOptional()

        SQTextField("Label name", text: .constant(""))
            .sqPlaceholder("Placeholder")
            .disabled(true)

        SQTextField("Label name", text: .constant(""))
            .sqPlaceholder("Placeholder")

        // Note: .sqIcon() must be called BEFORE other modifiers to work correctly
        SQTextField("Label with icon", text: .constant(""))
            .sqIcon(SQIcon(.magnifying_glass, color: .sqNeutral(80)))
            .sqPlaceholder("Placeholder")

        SQTextField("Numéro de RCS", text: .constant(""))
            .sqPlaceholder("RCS VILLE B 123456789")
            .sqOptional()
            .sqTooltipText("Vous pouvez trouver votre numéro RCS sur l'extrait Kbis de votre entreprise ou votre extrait K, si vous êtes un entrepreneur individuel.\n\nLe numéro RCS se compose tout d'abord de la mention RCS, puis du numéro d'immatriculation de la ville dans laquelle a été créée la société, d'une lettre et enfin du numéro SIREN à 9 chiffres.")
    }
    .padding()
}
