//
//  DetailBookViewController.swift
//  MyBookshelf
//
//  Created by gukhyeon.gyeong on 2021/04/07.
//

import UIKit

class DetailBookViewController: BaseUIViewController, LoadingProtocol {
    
    //
    // MARK: Constants
    //
    
    //
    // MARK: Properties
    //
    
    internal let viewModel: BookViewModel
    
    //
    // MARK: Views
    //
    
    private let scrollView: UIScrollView = {
        let view = UIScrollView()
        view.backgroundColor = .clear
        view.alwaysBounceVertical = true
        view.showsVerticalScrollIndicator = true
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let containerView: UIStackView = {
        let view = UIStackView()
        view.axis = .vertical
        view.distribution = .equalSpacing
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let thumbnailImageView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        view.backgroundColor = .clear
        
        view.layer.shadowOffset = .zero
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowRadius = 8
        view.layer.shadowOpacity = 0.2
        view.clipsToBounds = false
        
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let bottomShadowView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        view.layer.shadowColor = UIColor.black.cgColor
        view.layer.shadowRadius = 8
        view.layer.shadowOpacity = 0.2
        view.clipsToBounds = false
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let buyButton: UIButton = {
        let view = UIButton(type: .custom)
        view.titleLabel?.font = .boldSystemFont(ofSize: 15)
        view.setTitleColor(.white, for: .normal)
        view.backgroundColor = .gray
        view.layer.cornerRadius = 4
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    
    //
    // MARK: Initializers
    //
    init(with book: Book) {
        self.viewModel = BookViewModel(with: book)
        super.init(nibName: nil, bundle: nil)
        
        self.viewModel.delegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension DetailBookViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.viewModel.fetchInfo()
    }
}
   
extension DetailBookViewController {
    
    override func setupUI() {
        
        self.view.backgroundColor = .white
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .compose,
                                                                 target: self,
                                                                 action: #selector(addNoteButtonTouched))
        
        self.navigationItem.rightBarButtonItem?.tintColor = .primary
        
        self.view.addSubviews([scrollView, bottomShadowView, bottomView])
    
        scrollView.addSubview(containerView)
        bottomView.addSubview(buyButton)
        
        // for update with initial data before fetching data
        self.updateUI()
    }
    
    
    override func setupLayout() {
        
        // scrollView
        scrollView.bottomAnchor.constraint(equalTo: bottomView.topAnchor).isActive = true
        if #available(iOS 11.0, *) {
            scrollView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
            scrollView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
            scrollView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor).isActive = true
            
        } else {
            scrollView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
            scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
            scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        }
        
        // containerView
        containerView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
        containerView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        containerView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        containerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
        
        // thumbnailImageView
        thumbnailImageView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
        thumbnailImageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
        
        // bottomView
        bottomView.heightAnchor.constraint(equalToConstant: 60).isActive = true
        bottomView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        bottomView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        if #available(iOS 11.0, *) {
            bottomView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        } else {
            bottomView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
            
        }
        
        // buyButton
        buyButton.centerYAnchor.constraint(equalTo: bottomView.centerYAnchor).isActive = true
        buyButton.heightAnchor.constraint(equalToConstant: 48).isActive = true
        if #available(iOS 11.0, *) {
            buyButton.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 15).isActive = true
            buyButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -15).isActive = true
        } else {
            buyButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
            buyButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15).isActive = true
        }
        
        
        // bottomShadowView
        bottomShadowView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        bottomShadowView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        bottomShadowView.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
        bottomShadowView.bottomAnchor.constraint(equalTo: bottomView.topAnchor).isActive = true
    }
    
    
    override func updateFrame() {
        
        let shadowBounds = CGRect(x: 0,
                                  y: 0,
                                  width: self.bottomShadowView.bounds.width,
                                  height: 10)
        self.bottomShadowView.layer.shadowPath = UIBezierPath(rect: shadowBounds).cgPath
    }
    
    
    override func setupAction() {
        buyButton.addTarget(self, action: #selector(self.buyButtonTouched), for: .touchUpInside)
    }
}


extension DetailBookViewController {
    func updateUI() {
        
        // thubmnail
        self.viewModel.requestThumbnail()
        
        // buy button
        if let price = self.viewModel.bookData.price, let _ = self.viewModel.bookData.itemUrl {
            self.buyButton.setTitle("Buy \(price)", for: .normal)
            self.buyButton.backgroundColor = .primary
        } else {
            self.buyButton.setTitle("Sold out", for: .normal)
            self.buyButton.backgroundColor = .gray
        }
        
        // remove previous info
        containerView.subviews.forEach {
            containerView.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        
        // add basic info
        self.addContentViews(contents: [thumbnailImageView,
                                        self.titleInfoView,
                                        self.subTitleInfo,
                                        self.authorInfo,
                                        self.publisherInfo,
                                        self.isbn13Info,
                                        self.isbn10Info,
                                        self.ratingInfo,
                                        self.yearInfo,
                                        self.pagesInfo,
                                        
        ])
        
        // add pdf info
        self.addContentViews(contents: self.pdfInfoList)
        
        // add description info
        self.addContentViews(contents: [self.descriptionInfo])
        
        // add notes info
        self.addContentViews(contents: self.noteInfoList)
    }
    
    
    private func addContentViews(contents: [UIView?]) {
        contents.forEach { [weak self] in
            self?.addContentView(content: $0)
        }
    }
    
    // add arranged subview with auto layout
    private func addContentView(content: UIView?) {
        guard let content = content else { return }
        self.containerView.addArrangedSubview(content)
        content.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true
        content.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true
    }
}




extension DetailBookViewController: BookViewModelDelegate {
    func receivedError(with error: Error, isbn: String) {
        self.showMessage(title: "Error", message: error.localizedDescription) { [weak self] _ in
            self?.navigationController?.popViewController(animated: true)
        }
    }
    
    func receivedThumbnail(with image: UIImage?, isbn: String) {
        self.thumbnailImageView.image = image
    }
    
    func dataRefreshed(isbn: String) {
        self.updateUI()
    }
    
    func lodingChanged(with value: Bool, isbn: String) {
        if value {
            self.showLoading()
        } else {
            self.hideLoading()
        }
    }
    
    func notesChanged(isbn: String) {
        self.updateUI()
        self.view.layoutIfNeeded()
        self.scrollView.scrollToBottom()
    }
}





extension DetailBookViewController {
    @objc private func buyButtonTouched() {
        self.openLink(link: viewModel.bookData.itemUrl)
    }
    
    @objc private func addNoteButtonTouched() {
        let vc = InputNoteViewController(with: self.viewModel)
        let navVC = UINavigationController(rootViewController: vc)
        self.present(navVC, animated: true, completion: nil)
    }
}



extension DetailBookViewController {
    internal func openLink(link: String?) {
        guard let link = link, let url = URL(string: link) else { return }
        
        let vc = WebViewController(with: url)
        let nav = UINavigationController(rootViewController: vc)
        nav.navigationBar.tintColor = .darkGray
        
        self.present(nav, animated: true, completion: nil)
    }
}
