//
//  HalfView.swift
//  PersonalHealthDiary
//
//  Created by Sean Kim on 3/6/24.
//

import SwiftUI

//struct HalfView: View {
//    @State var showSheet: Bool = false
//    
//    var body: some View {
////            NavigationView {
//        Button {
//            showSheet.toggle()
//        } label: {
//            Text("Button Click2")
//        }
//        .halfSheet(showSheet: $showSheet) {
//            Text("HELLO HALF")
//        } onEnd: {
//            print("?")
//        }
//        //            }
//    }
//}

extension View {
    func halfSheet<SheetView: View>(showSheet: Binding<Bool>, @ViewBuilder sheetView: @escaping ()->SheetView, onEnd: @escaping ()->() ) -> some View {
        return self
            .background(
                //  사용하는 이유로는 스유의 사이즈로만 사용할것이니까
                HalfSheetHelper(sheetView: sheetView(), showSheet: showSheet, onEnd: onEnd)
            )
    }
}

//UIKit을 써야 하는것 같음
struct HalfSheetHelper<SheetView: View>: UIViewControllerRepresentable {
    
    var sheetView: SheetView
    @Binding var showSheet: Bool
    var onEnd: ()->()
    // 나중에 호출시 이거 순서 따라서 인수 위치도 바뀜
    
    let vc = UIViewController()
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    func makeUIViewController(context: Context) -> UIViewController {
        vc.view.backgroundColor = .clear
        return vc
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if showSheet {
            let sheetController = CustomHostingController(rootView: sheetView)
            sheetController.presentationController?.delegate = context.coordinator
            uiViewController.present(sheetController, animated: true)
        }
        else {
            // showSheet 가 토글 되어 view 가 닫힐 때
//            uiViewController.dismiss(animated: true)
            uiViewController.presentedViewController?.dismiss(animated: true)
        }
    }
    
    // 종료
    class Coordinator: NSObject, UISheetPresentationControllerDelegate {
        
        var parent: HalfSheetHelper
        
        init(parent: HalfSheetHelper) {
            self.parent = parent
        }
        
        func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
            parent.showSheet = false
            parent.onEnd()
        }
    }
}

class CustomHostingController<Content: View>: UIHostingController<Content> {
    override func viewDidLoad() {
//        view.backgroundColor = .clear
        // 보여주는 컨트롤러의 프로퍼티 설정 부
        if let presentationController = presentationController as? UISheetPresentationController {
            presentationController.detents = [.medium()]
            // 모달 뷰 위에 작게 바 표시 있는거
            presentationController.prefersGrabberVisible = false
        }
    }
}
