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

import SwiftUI

// MARK: - SQTextFieldBase

/// Base component for all Sequoia text field variants.
/// Provides common functionality: label, error display, character count, tooltip, styling, etc.
///
/// This component uses `@Environment` to read configuration set via View Modifiers,
/// following the same pattern as native SwiftUI components.
struct SQTextFieldBase<Content: View>: View {
    private let label: String
    @Binding var isFocused: Bool
    var textCount: Int
    let content: Content

    @Environment(\.sqTextFieldConfiguration) private var config
    @State private var showTooltip = false

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

    init(
        _ label: String,
        isFocused: Binding<Bool>,
        textCount: Int,
        @ViewBuilder content: () -> Content
    ) {
        self.label = label
        self._isFocused = isFocused
        self.textCount = textCount
        self.content = content()
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            // Label with tooltip/info
            HStack(spacing: 8) {
                SQText(label)
                    .sqFont(.semiBold)
                    .sqColor(.sqNeutral(80))

                if let tooltipText = config.tooltipText {
                    Button {
                        withAnimation {
                            showTooltip.toggle()
                        }
                    } label: {
                        SQIcon(.circle_info, color: .sqNeutral(80))
                    }
                    .overlay(
                        Group {
                            if showTooltip {
                                SQTooltip(text: tooltipText, isVisible: $showTooltip)
                                    .fixedSize()
                            }
                        }
                    )
                    .accessibilityLabel("Information")
                    .accessibilityHint("Appuyez deux fois pour afficher plus d'informations")
                } else if let infoAction = config.infoAction {
                    Button {
                        infoAction()
                    } label: {
                        SQIcon(.circle_info, color: .sqNeutral(80))
                    }
                    .accessibilityLabel("Information")
                    .accessibilityHint("Appuyez deux fois pour afficher plus d'informations")
                }

                Spacer()

                if config.isOptional {
                    SQText("Optionnel")
                        .sqSize(12)
                        .sqColor(.sqNeutral(50))
                }
            }

            // Content (TextField/SecureField/custom)
            content
                .padding(16)
                .foregroundStyle(Color.sqNeutral())
                .background {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(config.isDisabled ? Color.sqNeutral(10) : config.backgroundColor)
                }
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .inset(by: 0.5)
                        .stroke(
                            config.error.wrappedValue.isInError ? .sqSemanticRed :
                                isFocused ? accentColor :
                                config.isDisabled ? Color.sqNeutral(20) : Color.sqNeutral(30),
                            lineWidth: 1
                        )
                )

            // Error / Helper / Character count
            HStack(spacing: 16) {
                if config.error.wrappedValue.isInError {
                    HStack(spacing: 4) {
                        SQIcon(.circle_exclamation, customSize: 12, type: .solid, color: .sqSemanticRed)
                        SQText(config.error.wrappedValue.message)
                            .sqSize(12)
                            .sqColor(.sqSemanticRed)
                    }
                } else if let helperText = config.helperText {
                    SQText(helperText)
                        .sqSize(12)
                        .sqColor(.sqNeutral(50))
                }

                Spacer()

                if !characterCountText.isEmpty && config.showCharacterCount {
                    SQText(characterCountText)
                        .sqSize(12)
                        .sqColor(.sqNeutral(50))
                }
            }
        }
        .disabled(config.isDisabled)
        .overlay(
            Group {
                if showTooltip {
                    Color.black.opacity(0.001)
                        .onTapGesture {
                            withAnimation {
                                showTooltip = false
                            }
                        }
                }
            }
        )
    }

    // MARK: - Helper Properties

    private var characterCountText: String {
        let count = textCount
        if let min = config.minCharacters, count < min {
            return "\(count)/\(min) min."
        } else if let max = config.maxCharacters {
            return count >= (max * 4 / 5) ? "\(count)/\(max) max." : "\(count)"
        }
        return ""
    }
}

// MARK: - Placeholder Extension

extension View {
    func placeholder<Content: View>(
        when shouldShow: Bool,
        alignment: Alignment = .leading,
        @ViewBuilder placeholder: () -> Content
    ) -> some View {
        ZStack(alignment: alignment) {
            placeholder().opacity(shouldShow ? 1 : 0)
            self
        }
    }
}
