//
//  UIView.swift
//  AcaMate
//
//  Created by Sean Kim on 12/14/24.
//

import SwiftUI
import UIKit

struct FixedSizeWrapper<Content: UIView>: UIViewRepresentable {
    let content: () -> Content
    let width: CGFloat
    let height: CGFloat
    
    func makeUIView(context: Context) -> Content {
        let view = content()
        view.translatesAutoresizingMaskIntoConstraints = false
        
        
        NSLayoutConstraint.activate([
            view.widthAnchor.constraint(equalToConstant: width),
            view.heightAnchor.constraint(equalToConstant: height)
        ])
        return view
    }
    
    func updateUIView(_ uiView: Content, context: Context) {}
}

struct CustomTxfView: View {
       
    var placeholder: String
    @Binding var text: String
    
    var maxLength: Int = 100
    var isSecure: Binding<Bool> = .constant(false)
    var alignment: TextAlignment = .leading
    
    var textColor = Color(.Text.detail)
    var font: Font = .nps(size:16)
//    UIFont(name: "NPS-font-Regular", size: 16)
    
    
    var body: some View {
        TextField(placeholder, text: $text)
//                    Binding<String>(
//            get: { text },
//            set: { newValue in
//                text = String(newValue.prefix(maxLength))
//            }
//        ))
        .font(font)
        .tint(textColor)
        .lineLimit(1)
        .multilineTextAlignment(alignment)
        .minimumScaleFactor(0.5)
        .truncationMode(.tail)
        .clipped()
        
        .onChange(of: text) { old, new in
            if new.count > maxLength {
                text = String(new.prefix(maxLength))
            }
        }
    }
}


struct CustomTextField: UIViewRepresentable {
    var placeholder: String
    @Binding var text: String
    var maxLength: Int?
    var isSecure: Binding<Bool> = .constant(false)
    
    var textColor = UIColor(Color(.Text.detail))
    var font = UIFont(name: "NPS-font-Regular", size: 16)
    var alignment: NSTextAlignment = .left
    
    // [필수] 초기화 시 UIView 생성
    func makeUIView(context: Context) -> UITextField {
        let txf = UITextField()
        
        
        //        txf.placeholder = placeholder
        txf.attributedPlaceholder = NSAttributedString(
            string: "\(placeholder)",
            attributes: [NSAttributedString.Key.foregroundColor : UIColor(.Text.border)])
        
        txf.isSecureTextEntry = isSecure.wrappedValue
        
        txf.adjustsFontSizeToFitWidth = true
        txf.minimumFontSize = 4
        
        txf.textColor = textColor
        let height = (font?.lineHeight ?? 10) + 8
        txf.frame.size.height = height
        
        txf.borderStyle = .none
        txf.autocorrectionType = .no
        txf.autocapitalizationType = .none
        txf.smartInsertDeleteType = .no
        txf.textContentType = .oneTimeCode
        txf.textAlignment = self.alignment
        txf.translatesAutoresizingMaskIntoConstraints = false
        txf.setContentHuggingPriority(.required, for: .horizontal)
        txf.setContentCompressionResistancePriority(.required, for: .horizontal)
        
        txf.delegate = context.coordinator
        return txf
    }
    
    // [필수] 스유 상태 변화 따라 UIView 업데이트
    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
        uiView.isSecureTextEntry = isSecure.wrappedValue
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self, max: maxLength)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: CustomTextField
        var maxLength: Int?
        
        init(_ parent: CustomTextField, max: Int?) {
            self.parent = parent
            self.maxLength = max
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            let current = textField.text ?? ""
            guard let stringRange = Range(range, in: current) else { return false}
            let updated = current.replacingCharacters(in: stringRange, with: string)
            return updated.count <= (maxLength ?? 9999)
        }
        
        //        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //            let currentText = textField.text ?? ""
        //            guard let stringRange = Range(range, in: currentText) else { return false }
        //            let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        //            return updatedText.count <= maxLength
        //        }
    }
    
}
