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

import SwiftUI
import UIKit

struct CustomTextField: UIViewRepresentable {
    var placeholder: String
    @Binding var text: String
    
    var isSecure: Binding<Bool> = .constant(false)
    
    var textColor = UIColor(Color(.Text.detail))
    var font = UIFont(name: "NPS-font-Regular", size: 16)
    
    // [필수] 초기화 시 UIView 생성
    func makeUIView(context: Context) -> UITextField {
        let txf = UITextField()
        txf.placeholder = placeholder
        txf.isSecureTextEntry = isSecure.wrappedValue

        txf.textColor = textColor
        txf.font = font
        
        txf.translatesAutoresizingMaskIntoConstraints = false
        
        let height = (font?.lineHeight ?? 10) + 8
        txf.frame.size.height = height
        
        txf.autocorrectionType = .no
        txf.autocapitalizationType = .none
        txf.smartInsertDeleteType = .no
        txf.textContentType = .oneTimeCode
        
        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)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: CustomTextField
        
        init(_ parent: CustomTextField) {
            self.parent = parent
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }
    }
    
}
