//
//  InputTextArea.swift
//  Pods
//
//  Created by dung.pham2 on 2/12/24.
//
import SwiftUI

// Make these constants public
public let MAX_LENGTH = 300
public let DEFAULT_HEIGHT: CGFloat = 104

struct UITextViewWrapper: UIViewRepresentable {
    @Binding var text: String
    var onDone: (() -> Void)?
    var onFocus: (() -> Void)?
    var onBlur: (() -> Void)?
    
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.delegate = context.coordinator
        return textView
    }
    
    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UITextViewDelegate {
        var parent: UITextViewWrapper
        
        init(_ parent: UITextViewWrapper) {
            self.parent = parent
        }
        
        func textViewDidChange(_ textView: UITextView) {
            parent.text = textView.text
        }
        
        func textViewDidBeginEditing(_ textView: UITextView) {
            parent.onFocus?()
        }
        
        func textViewDidEndEditing(_ textView: UITextView) {
            parent.onBlur?()
        }
        
        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            if text == "\n" {
                parent.onDone?()
                return false
            }
            return true
        }
    }
}

// Make the struct public
public struct InputTextArea: View {
    @Binding var text: String
    var maxLength: Int = MAX_LENGTH
    var height: CGFloat = DEFAULT_HEIGHT
    var floatingValue: String = ""
    var floatingValueColor: Color = .gray
    var floatingIcon: String = ""
    var floatingIconColor: Color = .black
    var placeholder: String = ""
    var onChangeText: (String) -> Void = { _ in }
    var error: String = ""
    var errorSpacing: Bool = false
    var disabled: Bool = false
    var icon: String = ""
    var iconColor: Color = .black
    var onRightIconPressed: () -> Void = {}
    var onFocus: () -> Void = {}
    var onBlur: () -> Void = {}
    var loading: Bool = false
    var required: Bool = false
    var fontWeight: Font.Weight = .regular
    var keyboardType: UIKeyboardType = .default
    
    @State private var isFocused = false
    @State private var isBlurred = false
    
    // Make the initializer public
    public init(
        text: Binding<String>,
        maxLength: Int = MAX_LENGTH,
        height: CGFloat = DEFAULT_HEIGHT,
        floatingValue: String = "",
        floatingValueColor: Color = .gray,
        floatingIcon: String = "",
        floatingIconColor: Color = .black,
        placeholder: String = "",
        onChangeText: @escaping (String) -> Void = { _ in },
        error: String = "",
        errorSpacing: Bool = false,
        disabled: Bool = false,
        icon: String = "",
        iconColor: Color = Colors.pink03,
        onRightIconPressed: @escaping () -> Void = {},
        onFocus: @escaping () -> Void = {},
        onBlur: @escaping () -> Void = {},
        loading: Bool = false,
        required: Bool = false,
        fontWeight: Font.Weight = .regular,
        keyboardType: UIKeyboardType = .default
    ) {
        self._text = text
        self.maxLength = maxLength
        self.height = height
        self.floatingValue = floatingValue
        self.floatingValueColor = floatingValueColor
        self.floatingIcon = floatingIcon
        self.floatingIconColor = floatingIconColor
        self.placeholder = placeholder
        self.onChangeText = onChangeText
        self.error = error
        self.errorSpacing = errorSpacing
        self.disabled = disabled
        self.icon = icon
        self.iconColor = iconColor
        self.onRightIconPressed = onRightIconPressed
        self.onFocus = onFocus
        self.onBlur = onBlur
        self.loading = loading
        self.required = required
        self.fontWeight = fontWeight
        self.keyboardType = keyboardType
    }
    
    public var body: some View {
        VStack(alignment: .leading, spacing: 0) {
                    ZStack(alignment: .topLeading) {
                        if !floatingValue.isEmpty || !floatingIcon.isEmpty {
                            HStack(spacing: 4) {
                                Text(floatingValue)
                                    .font(.caption)
                                    .foregroundColor(disabled ? .gray : floatingValueColor)
                                
                                if required {
                                    Text("*")
                                        .font(.caption)
                                        .foregroundColor(.red)
                                }
                                
                                if !floatingIcon.isEmpty {
                                    Image(systemName: floatingIcon)
                                        .font(.caption)
                                        .foregroundColor(disabled ? .gray : floatingIconColor)
                                }
                            }
                            .padding(.horizontal, 8)
                            .background(Colors.black01)
                            .offset(x: Spacing.S, y: -height / 10)
                            .zIndex(10)
                        }
                        
                        VStack {
                            ZStack(alignment: .topLeading) {
                                if text.isEmpty {
                                    Text(placeholder)
                                        .foregroundColor(disabled ? .gray : .gray)
                                        .font(.system(size: 16, weight: fontWeight))
                                        .padding(.horizontal, 16)
                                        .padding(.vertical, 12)
                                }
                                
                                UITextViewWrapper(text: $text, onDone: {
                                    // Handle done action if needed
                                },
                                onFocus: {
                                    isFocused = true
                                    onFocus()
                                }, onBlur: {
                                    isFocused = false
                                    isBlurred = true
                                    onBlur()
                                })
                                .frame(height: height)
                                .padding(.horizontal, 12)
                                .padding(.vertical, 8)
                                .disabled(disabled)                            }
                            
                            HStack {
                                Spacer()
                                Text("\(text.count)/\(maxLength)")
                                    .font(.caption)
                                    .foregroundColor(.gray)
                            }
                            .padding(.horizontal, 16)
                            .padding(.bottom, 12)
                        }
                        .background(Color.white)
                        .cornerRadius(8)
                        .overlay(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(borderColor, lineWidth: 1)
                        )
                    }
                    
                    if !error.isEmpty {
                        Text(error)
                            .font(.caption)
                            .foregroundColor(.red)
                            .padding(.top, errorSpacing ? 8 : 4)
                    }
                }
                .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
                    if !isBlurred {
                        isFocused = true
                        onFocus()
                    }
                }
                .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
                    if isFocused {
                        isFocused = false
                        isBlurred = true
                        onBlur()
                    }
                }
    }
    
    private var borderColor: Color {
        if disabled {
            return Colors.black03
        } else if !error.isEmpty {
            return .red
        } else if isFocused {
            return Colors.pink03
        } else {
            return Colors.border
        }

    }
}


