//
/*
 * Copyright (c) 2023 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import SwiftUI
import UIKit


protocol FeatureBannerDelegate {
    func didPressClose()
    func didPressShowDetails()
}

@objcMembers class FeatureBannerViewCell<Content: View>: UITableViewCell, FeatureBannerDelegate {
    private var parentViewController: UIViewController?
    private let hostingController = UIHostingController<Content?>(rootView: nil)
    private var webViewController: WebViewViewController?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        hostingController.view.backgroundColor = UIColor.clear
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func setupView(parent: UIViewController, rootView: Content) {
        self.parentViewController = parent
        hostingController.rootView = rootView
        
        let shouldControllerMove = hostingController.parent != parent
            if shouldControllerMove {
                removeController()
                parent.addChild(hostingController)
            }
        
        if !self.contentView.subviews.contains(hostingController.view) {
            self.contentView.addSubview(hostingController.view)
            self.contentView.vc_addSubViewMatchingParentSafeArea(hostingController.view)
        }
        
        if shouldControllerMove {
            hostingController.didMove(toParent: parent)
        }
    }
    
    func calculateHeight() -> CGFloat {
        hostingController.view.setNeedsLayout()
        hostingController.view.layoutIfNeeded()
        let result = hostingController.view.intrinsicContentSize.height
        
        return result
    }
    
    private func removeController() {
        hostingController.willMove(toParent: nil)
        hostingController.view.removeFromSuperview()
        hostingController.removeFromParent()
        parentViewController = nil
    }
    
    deinit {
        removeController()
    }
    
    
    // MARK: user interaction
    
    func hideTopBanner() {
        removeController()
        NotificationCenter.default.post(name: .bwiHideTopBanner, object: self, userInfo: ["type" : "feature_banner"])
    }
    
    func didPressClose() {
        hideTopBanner()
    }
    
    func didPressShowDetails() {
        let htmlFile = BWIBuildSettings.shared.bwiFeatureHistoryFilePath
        self.webViewController = WebViewViewController(localHTMLFile: htmlFile)
        webViewController?.title = BWIL10n.bwiSettingsNewFeaturesHeader
        let navigationBar: UINavigationController = UINavigationController(rootViewController: webViewController!)
        webViewController?.navigationItem.setLeftBarButton(UIBarButtonItem(title: VectorL10n.close, style: .plain, target: self, action: #selector(closeModal)), animated: false)
        hostingController.parent?.present(navigationBar, animated: true, completion: { () -> Void in
            self.hideTopBanner()
        })
    }
    
    @objc func closeModal() {
        webViewController?.dismiss(animated: true)
    }
}


struct FeatureBannerView: View {
    var delegate: FeatureBannerDelegate?
    
    var body: some View {
        VStack(alignment: .center) {
            closeButton
            header
            advertisementText
            showMoreButton
        }
        .background(Color(ThemeService.shared().theme.tintColor))
        .cornerRadius(12)
        .padding(16)
    }
    
    var header: some View {
        HStack() {
            Image(Asset.Images.newFeatures.name)
                .renderingMode(.template)
                .foregroundColor(Color(ThemeService.shared().theme.backgroundColor))
            Text(BWIL10n.bwiFeatureBannerHeader)
                .font(.system(size: 20).bold())
                .foregroundColor(Color(ThemeService.shared().theme.backgroundColor))
        }
    }
    
    var advertisementText: some View {
        Text(BWIL10n.bwiFeatureBannerAdvertisementText)
            .font(.system(size: 15))
            .multilineTextAlignment(.center)
            .lineLimit(nil)
            .foregroundColor(Color(ThemeService.shared().theme.backgroundColor))
            .padding(5)
    }
    
    var closeButton: some View {
        HStack() {
            Spacer()
            Button {
                delegate?.didPressClose()
            } label: {
                Image(Asset.Images.closeButton.name)
                    .renderingMode(.template)
                    .foregroundColor(Color(ThemeService.shared().theme.backgroundColor))
                    .padding(10)
            }
        }
    }
    
    var showMoreButton: some View {
        Button {
            delegate?.didPressShowDetails()
        } label: {
            Text(BWIL10n.bwiFeatureBannerShowMoreButton)
                .font(.system(size: 15))
                .padding(10)
                .foregroundColor(Color(ThemeService.shared().theme.backgroundColor))
                .overlay(RoundedRectangle(cornerRadius: 12)
                    .stroke(Color(ThemeService.shared().theme.backgroundColor), lineWidth: 2))
        }
        .padding(.top, 10)
        .padding(.bottom, 25)
    }
    
}
