//
//  SQTextEditor.swift
//  AlloVoisinsSwiftUI
//
//  Created by Victor on 27/11/2024.
//

import SwiftUI

struct SQTextEditor: View {
    var label: String
    var placeholder: String
    var error: Binding<SQFormFieldError>
    var icon: SQIcon?
    var isDisabled: Bool = false
    var isOptional: Bool = false
    var tooltipText: String?
    var minCharacters: Int?
    var maxCharacters: Int?
    @Binding var text: String
    @FocusState private var isFocused: Bool
    @State private var showTooltip = false
    let infoAction: (() -> Void)?
    let iconAction: (() -> Void)?

    private var accentColor: Color = .sqNeutral(80)

    init(_ label: String,
         placeholder: String,
         error: Binding<SQFormFieldError> = .constant(.none),
         text: Binding<String>,
         icon: SQIcon? = nil,
         isDisabled: Bool = false,
         isOptional: Bool = false,
         tooltipText: String? = nil,
         minCharacters: Int? = nil,
         maxCharacters: Int? = nil,
         infoAction: (() -> Void)? = nil,
         iconAction: (() -> Void)? = nil)
    {
        self.label = label
        self.placeholder = placeholder
        self.error = error
        self._text = text
        self.icon = icon
        self.isDisabled = isDisabled
        self.isOptional = isOptional
        self.tooltipText = tooltipText
        self.minCharacters = minCharacters
        self.maxCharacters = maxCharacters
        self.infoAction = infoAction
        self.iconAction = iconAction
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            HStack(spacing: 8) {
                SQText(label)
                Spacer()
                if isOptional {
                    SQText("Optionnel")
                        .sqSize(12)
                        .sqColor(.sqNeutral(50))
                }
            }
            TextEditor(text: Binding(
                get: { self.text },
                set: { self.text = String($0.prefix(self.maxCharacters ?? Int.max)) }
            ))
            .onChange(of: self.text, perform: { _ in
                error.wrappedValue = .none
            })
            .font(.sq(.medium))
            .foregroundStyle(Color.sqNeutral(100))
            .tint(accentColor)
            .frame(height: 108)
            .foregroundStyle(Color.sqNeutral())
            .background(isDisabled ? Color.sqNeutral(10) : .clear)
            .padding(16)
            .overlay(
                RoundedRectangle(cornerRadius: 8)
                    .inset(by: 0.5)
                    .stroke(error.wrappedValue.isInError ? .sqSemanticRed : isFocused ? accentColor : isDisabled ? Color.sqNeutral(20) : Color.sqNeutral(30), lineWidth: 1)
            )
            HStack(spacing: 16) {
                if error.wrappedValue.isInError {
                    HStack(spacing: 8) {
                        SQIcon(.circle_exclamation, customSize: 12, type: .solid, color: .sqSemanticRed)
                        SQText(error.wrappedValue.message)
                            .sqSize(12)
                            .sqFont(.semiBold)
                            .sqColor(.sqSemanticRed)
                    }
                }
                Spacer()
                if !characterCountText.isEmpty {
                    SQText(characterCountText)
                        .sqSize(12)
                        .sqColor(.sqNeutral(50))
                }
            }
        }
    }

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

#Preview {
    SQTextEditor("Zone de texte", placeholder: "Ex : Pro Solutions propose une gamme de services complète pour tout type de dépannage électroménager. Bénéficiez de nos 10 ans d’expérience ! Devis gratuit", text: .constant("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."))
        .padding()
    SQTextEditor("Zone de texte", placeholder: "Ex : Pro Solutions propose une gamme de services complète pour tout type de dépannage électroménager. Bénéficiez de nos 10 ans d’expérience ! Devis gratuit", error: .constant(.empty), text: .constant("Lorem ipsum dolor sit amet, consectetur"), minCharacters: 50)
        .padding()
}
