//
//  ShopProductsVM.swift
//  WOKA
//
//  Created by MacBook Pro on 22/07/24.
//

import Foundation
import Alamofire

class ShopProductsVM{
    
    weak var vc : ShopProductsVC!
    var subCategoryData = [ShopSubCategoryDM.ResultData]()
    var shopProductsData = [ShopProductsListingDM.ResultData]()

    var categoryID : Int?
    var selectedSubCategory = 0
    var pageTitle : String?
    
    var pageNo = 0
    var stopFetch = false
    var cartButton: UIBarButtonItem!

    func initView(){
        getCategory()
        addGradient()
        setupCell()
        cartButton = BadgeBarBtn.shared.setupCartButton(target: self, action: #selector(cartButtonTapped))
        self.vc.navigationItem.rightBarButtonItem = cartButton
    }
    
    @objc func cartButtonTapped(){
        PersistentStorage.shared.addShopCount(postID: 0)

        if AuthFunc.shareInstance.guestUserLoginPopUp() { return}

        let sb = UIStoryboard(name: K.StoryBoard.cart, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Cart.cartListVC) as! CartListVC
        self.vc.navigationController?.pushViewController(vcPush, animated: true)
    }
    
    func addGradient(){
        let color1 = #colorLiteral(red: 0.6745098039, green: 0.6235294118, blue: 0.1725490196, alpha: 1)
        let color2 = #colorLiteral(red: 0.5450980392, green: 0.6745098039, blue: 0.1725490196, alpha: 1)
        self.vc.title = pageTitle ?? "Shop"
        vc.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
    }
    
    func setupCell(){
        vc.subCategoryCV.register(UINib(nibName: K.CellIdentifier.WebSeries.seasonCategoryCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.WebSeries.seasonCategoryCell)
        vc.subCategoryCV.delegate = vc.self
        vc.subCategoryCV.dataSource = vc.self
        
        vc.productCV.register(UINib(nibName: K.CellIdentifier.Shop.shopProductsCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.Shop.shopProductsCell)
        vc.productCV.delegate = vc.self
        vc.productCV.dataSource = vc.self
    }
    
    // MARK: - Get SuperCategory
    
    func getCategory(){
        guard let categoryID else{return}
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["category_id" : categoryID]
        
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Shop.sub_category_listing, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<ShopSubCategoryDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? K.ConstantString.unRecognised, time: 1.5)
                    self.vc.noDataStack.isHidden = false
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{
                        self.vc.noDataStack.isHidden = false
                        return
                    }
                    self.subCategoryData.append(ShopSubCategoryDM.ResultData(id: -1, categoryMasterID: 0, subCategoryName: " All ", subCategoryThumbnail: ""))
                    self.subCategoryData.append(contentsOf: data)
                    self.selectedSubCategory = -1
                    self.vc.subCategoryCV.reloadData()
                    if let subCatID = data.first?.id{
                        Utilities.startProgressHUD()
                        self.getShopProducts(subCategoryID: subCatID)
                    }
                    self.vc.noDataStack.isHidden = true
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 1.5)
                self.vc.noDataStack.isHidden = false
            }
        }
    }
    
    func getShopProducts(subCategoryID : Int?){
        guard let categoryID else{
            Utilities.dismissProgressHUD()
            return
        }
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["category_id" : categoryID,
                                   "sub_category_id" : ((subCategoryID == -1) ? "" : subCategoryID?.toString() ) ?? "",
                                   "api_version" : "v2",
                                   "start" : pageNo,
                                   "limit" : 12]
        
        // 11 - hindi , 12 - english
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Shop.shop_product_listing_v2, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<ShopProductsListingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    vc.spinnerView.stopAnimating()
                    if stopFetch == true { return}
                    Utilities.alertWithBtnCompletion(title: "Error", msgBody: data.message ?? K.ConstantString.unRecognised, okBtnStr: "Retry?", vc: self.vc) { isDone in
                        if isDone{
                            self.getShopProducts(subCategoryID: subCategoryID)
                        }
                    }
                case 1:
                    Utilities.dismissProgressHUD()
                    vc.spinnerView.stopAnimating()
                    guard let count = data.data?.totalRecords ,let data = data.data?.result else{return}
                    if pageNo == 0{
                        self.shopProductsData.removeAll()
                    }
                    self.shopProductsData.append(contentsOf: data)
                    self.vc.productCV.reloadData()
                    if self.shopProductsData.count == count{
                        stopFetch = true
                    }
                    
                    /*
                     check for single product
                     */
                    if self.shopProductsData.count == 1{
                        let sb = UIStoryboard(name: K.StoryBoard.shop, bundle: nil)
                        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Shop.productDetailsVC) as! ProductDetailsVC
                        if let productID = self.shopProductsData.first?.id{
                            vcPush.vm.productID = productID
                        }
                        self.vc.navigationController?.pushViewController(vcPush, animated: true)
                    }
                default:
                    Utilities.dismissProgressHUD()
                    vc.spinnerView.stopAnimating()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    self?.vc.spinnerView.stopAnimating()
                    return
                }
                Utilities.dismissProgressHUD()
                vc.spinnerView.stopAnimating()
                Utilities.alertWithBtnCompletion(title: "Error", msgBody: error.localizedDescription, okBtnStr: "Retry?", vc: self.vc) { isDone in
//                    if isDone{
//                        self.getCategory()
//                    }
                }
            }
        }
    }
}


class FooterSpinnerView: UICollectionReusableView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSpinner()
    }

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

    private func setupSpinner() {
        let spinner = UIActivityIndicatorView(style: .medium)
        spinner.translatesAutoresizingMaskIntoConstraints = false
        spinner.startAnimating()
        spinner.hidesWhenStopped = true
        spinner.color = UIColor.appColor(.TextDarkBlue)!
        addSubview(spinner)

        NSLayoutConstraint.activate([
            spinner.centerXAnchor.constraint(equalTo: centerXAnchor),
            spinner.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
    }
}
