//
//  WebView.swift
//  AcaMate
//
//  Created by TAnine on 3/24/25.
//

import SwiftUI
import WebKit

struct WebView: UIViewControllerRepresentable {
    
    
    var url: URL
    @Binding var showWebView: Bool
    @Binding var isLoading: Bool
    var complete: ((Any) -> Void)?
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
        var parent: WebView
        
        init(parent: WebView) {
            self.parent = parent
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("웹뷰 로딩 완료")
            parent.isLoading = false
            
        }
        
        func userContentController(_ userContentController: WKUserContentController,
                                   didReceive message: WKScriptMessage) {
            if let data = message.body as? [String: Any]
                {
                if let road = data["roadAddress"], let code = data["zonecode"] {
                    printLog("도로명 주소: \(road) // ZIP CODE: \(code)")
                    parent.complete?((road,code))
                }
            }
            parent.showWebView.toggle()
        }
    }
    
    
    func updateUIViewController(_ uiViewController: WebViewController, context: Context) {
    }
    
    func makeUIViewController(context: Context) -> WebViewController {
        return WebViewController(url: url, isLoading: $isLoading,
                                 complete: complete, coordinator: context.coordinator)
            
    }
    
    
}

class WebViewController: UIViewController, WKUIDelegate {
    
    var url: URL
    @Binding var isLoading: Bool
    var complete: ((Any) -> Void)?
    var coordinator: WebView.Coordinator

    init(url: URL, isLoading: Binding<Bool>, complete: ((Any) -> Void)?, coordinator: WebView.Coordinator) {
        self.url = url
        _isLoading = isLoading
        self.complete = complete
        self.coordinator = coordinator
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView()
    }
    
    private func webView() {
        let request = URLRequest(url: url)
        
        let configuration = WKWebViewConfiguration()
        let contentController = WKUserContentController()
        
        contentController.add(coordinator, name: "callBackHandler")
        configuration.userContentController = contentController
        
        let webview = WKWebView(frame: view.bounds, configuration: configuration)
        webview.uiDelegate = self
        webview.navigationDelegate = coordinator
        webview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        webview.isUserInteractionEnabled = true
        webview.scrollView.isUserInteractionEnabled = true
        webview.scrollView.delaysContentTouches = false

        webview.load(request)
        view.addSubview(webview)
        
    }
}
