//
// © 2018-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

struct BottomSheetViewControllerItem {
    let identifier: String
    let image: UIImage?
    let title: String
    let accessibilityTitle: String?
    let checked: Bool
}

import UIKit

protocol BottomSheetViewControllerDelegate: NSObjectProtocol {
    func bottomSheetViewController(_ viewController: BottomSheetViewController,
                                   didEndWithItem item: BottomSheetViewControllerItem?)
}

// MARK: -

class BottomSheetViewController: UIViewController {
    weak var delegate: BottomSheetViewControllerDelegate?

    // MARK: UI Outlets
    @IBOutlet private weak var stackView: UIStackView?
    @IBOutlet private weak var shadingView: UIView?
    @IBOutlet private weak var containerHeightLayoutConstraint: NSLayoutConstraint?
    @IBOutlet private weak var stackViewHeightLayoutConstraint: NSLayoutConstraint?
    @IBOutlet private weak var bottomOffsetLayoutConstraint: NSLayoutConstraint?
    private let stackViewItemHeight: CGFloat = 56.0
    var titleItem: BottomSheetViewControllerItem?;
    var optionItems: [BottomSheetViewControllerItem] = [];
    var initiatingIndexPath: IndexPath?
}

// MARK: - Overridden Methods
extension BottomSheetViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        bottomOffsetLayoutConstraint?.constant = -1000

        // Turn off bluring view if user doesn't want transparency
        // Normally it's black
        if UIAccessibility.isReduceTransparencyEnabled {
			shadingView?.backgroundColor = UIColor.clear
		}

        stackView!.spacing = -8

        // Add title view

        if let item = titleItem {
            let titleView = preparedItemView(item: item)
            titleView.imageViewLeftConstraint.constant = 8.0
            titleView.contentView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
            stackView?.addArrangedSubview(titleView)
        }
        // Add option views

        optionItems.forEach { item in
            let optionView = preparedItemView(item: item)
            optionView.imageViewLeftConstraint.constant = 24.0
            optionView.button.addTarget(self, action: #selector(buttonTapped(_ :)), for: .touchUpInside)
            optionView.backgroundColor = UIColor.white
            optionView.checkmark.isHidden = !item.checked
            stackView?.addArrangedSubview(optionView)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let stackViewHeight = CGFloat(optionItems.count + 1) * stackViewItemHeight
        var bottomPadding: CGFloat = 0.0
        if #available(iOS 11.0, *) {
            bottomPadding = view.safeAreaInsets.bottom
        }
        containerHeightLayoutConstraint?.constant = stackViewHeight + bottomPadding
        stackViewHeightLayoutConstraint?.constant = stackViewHeight
        bottomOffsetLayoutConstraint?.constant = -(stackViewHeight + bottomPadding)
        view.setNeedsLayout()
        view.layoutIfNeeded()

        self.bottomOffsetLayoutConstraint?.constant = 0
        UIView.animate(withDuration: 0.3,
                       animations: {
                        self.shadingView?.alpha = 0.5
                        self.view.layoutIfNeeded()
        })
    }
}

// MARK: - UI Actions
extension BottomSheetViewController {
    @objc func buttonTapped(_ sender: UIButton) {
        let idx = stackView?.arrangedSubviews.firstIndex(where: { view in
            if let itemView = view as? BottomSheetViewControllerItemView {
                return itemView.button === sender;
            } else {
                return false
            }
        })

        if let foundIdx = idx,
            foundIdx > 0 {
            animateOut(item: optionItems[foundIdx - 1])
        }
    }

    @IBAction private func didCloseGesture(_ sender: AnyObject?) {
        animateOut(item: nil)
    }
}

// MARK: - Private Methods
extension BottomSheetViewController {
    private func preparedItemView(item: BottomSheetViewControllerItem)->(BottomSheetViewControllerItemView) {
        let view = BottomSheetViewControllerItemView(frame: CGRect(x: 0, y: 0, width: 300, height: stackViewItemHeight))
        view.titleLabel.text = item.title
        if let accessibilityTitle = item.accessibilityTitle {
            if item.checked {
        		view.button.makeAccessible(accessibilityTitle + Accessibility.HomeScreen.SlideUpPanel.selectedSuffix)
            } else {
                view.button.makeAccessible(accessibilityTitle)
            }
        }
        if let img = item.image {
            view.imageView.image = img;
        }
        return view
    }

    private func animateOut(item: BottomSheetViewControllerItem?) {
        var bottomPadding: CGFloat = 0.0
        if #available(iOS 11.0, *) {
            bottomPadding = view.safeAreaInsets.bottom
        }
        bottomOffsetLayoutConstraint?.constant = -((stackView?.bounds.height)! + bottomPadding)
        UIView.animate(withDuration: 0.3,
                       animations: {
                        self.view.layoutIfNeeded()
                        self.shadingView?.alpha = 0
        },
                       completion: { [weak self] (Bool) in
                        guard let self = self else {
                            return
                        }
                        if let presenter = self.presentingViewController {
                            presenter.dismiss(animated: true, completion: {
                                self.delegate?.bottomSheetViewController(self,
                                                                               didEndWithItem: item)
                            })
                        }
        })
    }
}

