//
//  ProductCardViewController.swift
//  Sarawan
//
//  Created by Alex Misko on 28.07.2023.
//

import UIKit
import Combine

enum ElementsOfProductCard: String {
    case priceInOtherStoresCell
}

final class ProductCardViewController: UIViewController {

    
    // MARK: - Private Properties
    private let screenWidth = (UIScreen.main.bounds.size.width)
    private let screenHeight = (UIScreen.main.bounds.size.height)
    private var cancellable = Set<AnyCancellable>()
    private var popularProducts: [ProductModel] = []
    
    private var elementsOfProductCard: [ElementsOfProductCard] = [
        .priceInOtherStoresCell]

    var basketCache = [String: Int]()
    var favoritesCache = [String]()
    private var timer: Timer?
    // MARK: - Properties
    var storeAllName: [SearchHitSourceStore] = []
    var product: ProductModel
    let productCardView: ProductCardView
    let viewModel: ProductCardViewModel

    // MARK: - Init
    init(product: ProductModel, viewModel: ProductCardViewModel, view: ProductCardView) {
        self.productCardView = view
        self.product = product
        self.viewModel = viewModel
        self.storeAllName = product.storeAllName
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Lifecycle
    override func loadView() {
        super.loadView()
        self.view = productCardView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        getModelsFromApi()
        setupBindings()
        setupView()
        setupCacheBindings()
        addTargets()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isHidden = true
        fetchBasketCache()
        fetchFavoritesCache()
    }

    // MARK: - Private API
    private func getModelsFromApi() {
        viewModel.getAllPopularProducts(id: product.uuidProductInStore)
    }

        
    private func setupBindings() {
        productCardView.customNavigationBar.backButton.tapPublisher.sink(receiveValue: { [weak self] in
            self?.viewModel.isFinishScreen?()
        }).store(in: &cancellable)

        viewModel.popularProducts.sink(receiveValue: { popularProducts in
            self.popularProducts = popularProducts
            self.productCardView.recommendedProductView.popularProducts = popularProducts
            self.productCardView.recommendedProductView.collectionView.reloadData()
        }).store(in: &cancellable)
    }
    
    private func addTargets() {
        let tapgesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
                tapgesture.numberOfTapsRequired = 1
                self.productCardView.imageFoodView.addGestureRecognizer(tapgesture)
                self.productCardView.imageFoodView.isUserInteractionEnabled = true
    }
    
    private func setupView() {
        productCardView.customNavigationBar.title = product.category ?? ""
        view.backgroundColor = Asset.Colors.backgroundGray.color
        productCardView.configureProductImageView(product: self.product, onTapHeartButton: { isFavorite in
            self.product.isFavourite = isFavorite
                     let productId = self.product.uuidProduct
                     switch isFavorite {
                     case true:
                         self.viewModel.addToFavorite(product: productId)
                     case false:
                         self.viewModel.removeFromFavorite(product: productId)
                     }
        })

    }

    @objc func imageTapped(_ sender: UITapGestureRecognizer) {
        guard let imageView = sender.view as? UIImageView else { return }
        let newImageView = UIImageView(image: imageView.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = Asset.Colors.white.color
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)
        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true
    }

    @objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = false
        sender.view?.removeFromSuperview()
    }
}

extension ProductCardViewController {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let product = self.product
        
        switch elementsOfProductCard[indexPath.item] {
        case .priceInOtherStoresCell:
            let cell = collectionView
                .dequeueReusableCell(withReuseIdentifier: PriceInOtherStoresTableViewCell.identifire,
                                     for: indexPath) as! PriceInOtherStoresTableViewCell // swiftlint:disable:this force_cast
            cell.configureCell(storeAllName: product.storeAllName,
                               basketCache: basketCache,
                               onTappedBuyButton: { [weak self] (productId: String, count: Int) in
                                   self?.viewModel.onTapBuyButton.send((productId, count))
                                   self?.popularProducts[indexPath.item].inBasket = count
                               })
            return cell
        }
    }
}


// //MARK: - didSelect
//extension ProductCardViewController {
//    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        switch elementsOfProductCard[indexPath.item] {
//            //        case .productCardCell:
//            //            break
//        case .priceInOtherStoresCell:
//            break
//        case .recommendedProductCell:
//            let product = popularProducts[indexPath.row]
//            viewModel.onProductScreen?(product)
//        }
//    }
    //}
    //// MARK: UICollectionViewDataSource
    //extension ProductCardViewController: UICollectionViewDataSource {
    //    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //        return popularProducts.count
    //    }
    //
    //        func collectionView(_ collectionView: UICollectionView, // swiftlint:disable:this function_body_length
    //                            cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //            let product = self.product
    //
    //                if !popularProducts.isEmpty {
    //                    for index in 0...popularProducts.count-1 {
    //                        popularProducts[index].inBasket = 0
    //                        _ = self.basketCache.map({ key, value in
    //                            if popularProducts[index].uuidProductInStore == key {
    //                                popularProducts[index].inBasket = value
    //                            }
    //                        })
    //                    }
    //                }
    //
    //                return cell
    //            }
    //    }
    
    //    func collectionView(_ collectionView: UICollectionView, // swiftlint:disable:this function_body_length
    //                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //        let product = self.product
    //        switch elementsOfProductCard[indexPath.item] {
    //            //       case .productCardCell:
    //            //           let cell = collectionView
    //            //               .dequeueReusableCell(withReuseIdentifier: ProductCardCell.identifire,
    //            //                                    for: indexPath) as! ProductCardCell // swiftlint:disable:this force_cast
    //            //           cell.configureCell(product: product,
    //                              onTapHeartButton: { [weak self] isFavorite in
    //               guard let productId = self?.product.uuidProduct else { return }
    //               switch isFavorite {
    //               case true:
    //                   self?.viewModel.addToFavorite(product: productId)
    //                   self?.product.isFavourite = isFavorite
    //               case false:
    //                   self?.viewModel.removeFromFavorite(product: productId)
    //                   self?.product.isFavourite = isFavorite
    //               }
    //           })
    //           cell.promotionLabel.textColor = Asset.Colors.white.color
    //           cell.promotionLabel.layer.cornerRadius = 14
    //           cell.promotionLabel.clipsToBounds = true
    //           let tapgesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
    //               tapgesture.numberOfTapsRequired = 1
    //           cell.imageFoodView.addGestureRecognizer(tapgesture)
    //           cell.imageFoodView.isUserInteractionEnabled = true
    //           cell.layoutIfNeeded()
    //           return cell
    //        case .priceInOtherStoresCell:
    //            let cell = collectionView
    //                .dequeueReusableCell(withReuseIdentifier: PriceInOtherStoresCollectionViewCell.identifire,
    //                                     for: indexPath) as! PriceInOtherStoresCollectionViewCell // swiftlint:disable:this force_cast
    //            cell.configureCell(storeAllName: product.storeAllName,
    //                               basketCache: basketCache,
    //                               onTappedBuyButton: { [weak self] (productId: String, count: Int) in
    //                                   self?.viewModel.onTapBuyButton.send((productId, count))
    //                                   self?.popularProducts[indexPath.item].inBasket = count
    //                               })
    //
    //            return cell
    //        case .recommendedProductCell:
    //                    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecommendedProductCollectionCell.identifier, for: indexPath) as? RecommendedProductCollectionCell else { return UICollectionViewCell() }
    //
    //                    let recommendedProduct = popularProducts[indexPath.row]
    //                    cell.configure(recommendedProduct: recommendedProduct,
    //                                   products: popularProducts,
    //                                   onTapBuyButton: { [weak self] (productId: String, count: Int) in
    //                                       self?.viewModel.onTapBuyButton.send((productId, count))
    //                                       self?.popularProducts[indexPath.row].inBasket = count
    //                                   },
    //                                   onTapHeartButton: { [weak self] isFavorite in
    //                                       self?.viewModel.updateFavorites(productId: recommendedProduct.uuidProductInStore, isFavorite: isFavorite)
    //                                       self?.popularProducts[indexPath.row].isFavourite = isFavorite
    //                                   },
    //                                   onProductScreen: { [weak self] product in
    //                                       self?.viewModel.onProductScreen?(product)
    //                                   })
    //
    //                    cell.layoutIfNeeded()
    //                    return cell
    //            }
    //        }
        
    extension ProductCardViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let product = popularProducts[indexPath.row]
        viewModel.onProductScreen?(product)
        }
    }
    
    


    
    extension ProductCardViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView,
                            layout collectionViewLayout: UICollectionViewLayout,
                            insetForSectionAt section: Int) -> UIEdgeInsets {
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            switch indexPath.row {
            case 0:
                let height = screenWidth - 20
                return CGSize(width: screenWidth, height: height)
            case 1: let height: CGFloat = CGFloat(self.storeAllName.count*50) + CGFloat((self.storeAllName.count+1)*16)
                return CGSize(width: screenWidth, height: height)
            case 2: return CGSize(width: screenWidth, height: 269)
                
            default:
                return CGSize(width: screenWidth, height: 420)
            }
        }
    }
    
    extension ProductCardViewController: CacheableViewControllerProtocol {
        func fetchFavoritesCache() {
            viewModel.fetchFavoritesCache()
        }
        
        func fetchBasketCache() {
            viewModel.fetchBasketCache()
        }
        
        func setupCacheBindings() {
            viewModel.basketCache.sink(receiveValue: { [weak self] basketCache in
                self?.basketCache = basketCache
                self?.setupBasketCacheToProducts()
                self?.timer?.invalidate()
                self?.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { _ in
                    //                    self?.productCardView.recommendedProductView.collectionView.reloadData()
                })
            }).store(in: &cancellable)
            
            viewModel.favoritesCache.sink(receiveValue: { [weak self] favoritesCache in
                self?.favoritesCache = favoritesCache
                self?.setupFavoritesCacheToProducts()
                //                self?.productCardView.recommendedProductView.collectionView.reloadData()
            }).store(in: &cancellable)
        }
        
        func setupBasketCacheToProducts() {}
        
        func setupFavoritesCacheToProducts() {
            product.isFavourite = false
            _ = favoritesCache.map { uuid in
                if product.uuidProduct == uuid {
                    product.isFavourite = true
                }
            }
        }
    }
                                                                                            
В данном коде на экране не конфигурируется collectionView с ячейками priceInOtherStoresCell, помоги это исправить