//
//  SQCheckbox.swift
//  AlloVoisinsSwiftUI
//
//  Created by Victor on 25/11/2024.
//

import SwiftUI

struct SQCheckbox: View {
    var text: String
    @Binding var isChecked: Bool
    var error: Binding<SQFormFieldError>
    var alignment: VerticalAlignment = .top

    init(_ text: String, isChecked: Binding<Bool>, error: Binding<SQFormFieldError> = .constant(.none), alignment: VerticalAlignment = .top) {
        self.text = text
        self._isChecked = isChecked
        self.error = error
        self.alignment = alignment
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            HStack(alignment: alignment) {
                if isChecked {
                    SQImage("checked_neutral", height: 20)
                } else if error.wrappedValue.isInError {
                    SQImage("checkbox_unchecked_error", height: 20)
                } else {
                    SQImage("checkbox_unchecked", height: 20)
                }
                SQText(text)
            }
            .onTapGesture {
                isChecked.toggle()

                if error.wrappedValue.isInError && isChecked {
                    error.wrappedValue = .none
                }
            }

            HStack {
                SQIcon(.circle_exclamation, customSize: 13, type: .solid, color: .sqSemanticRed)
                SQText(error.wrappedValue.message)
                    .sqSize(12)
                    .sqFont(.semiBold)
                    .sqColor(.sqSemanticRed)
            }
            .isHidden(hidden: !error.wrappedValue.isInError)
        }
    }
}

#Preview {
    SQCheckbox("Je comprends que j’engage ma responsabilité sur l’exhaustivité et l’authenticité des informations renseignées ci-dessus.", isChecked: .constant(false))
    SQCheckbox("Je comprends que j’engage ma responsabilité sur l’exhaustivité et l’authenticité des informations renseignées ci-dessus.", isChecked: .constant(false), error: .constant(.empty))
}
