//
//  ProductDetailsVM.swift
//  WOKA
//
//  Created by Bilal on 26/07/2024.
//

import UIKit
import Alamofire

class ProductDetailsVM{
    
    weak var vc : ProductDetailsVC!
    
    var productDetails : ShopProductsListingDM.ResultData?
    var productID : Int?
    var cartButton: UIBarButtonItem!

    func initView(){
        addGradient()
        setupCell()
        
        cartButton = BadgeBarBtn.shared.setupCartButton(target: self, action: #selector(cartButtonTapped))
        self.vc.navigationItem.rightBarButtonItem = cartButton
        
        if let productID {
            self.getProductDetails(productID: productID)
        }
    }
    
    @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 updateView(){
        //set details
        if let productDetails{
            vc.productImageCV.reloadData()
            
            // 11 - hindi , 12 - english
            if productDetails.subCategoryMasterID == 12{
                vc.productTitle.text = productDetails.shopMasterDetail?.productNameEnglish
                if let desc = productDetails.shopMasterDetail?.descriptionEnglish, let htmlText = desc.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                    let sizeText = NSMutableAttributedString(attributedString: htmlText)
                    sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 16),color: UIColor.appColor(.TextDarkBlue)!)
                    vc.productDescription.attributedText = sizeText
                }
            }else{
                vc.productTitle.text = productDetails.shopMasterDetail?.productNameHindi
                if let desc = productDetails.shopMasterDetail?.descriptionHindi, let htmlText = desc.replacingOccurrences(of: "<br>", with: "").htmlToAttributedString{
                    let sizeText = NSMutableAttributedString(attributedString: htmlText)
                    sizeText.setFontFace(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Regular, size: 16),color: UIColor.appColor(.TextDarkBlue)!)
                    vc.productDescription.attributedText = sizeText
                }
            }
            
            vc.categoryName.text = productDetails.category?.categoryName
            vc.skuID.text = productDetails.skuID
            vc.productPrice.text = productDetails.productPrice
                        
            vc.pageControl.numberOfPages = productDetails.shopImage?.count ?? 1
            vc.pageControl.currentPage = 0
            if let addedToCart = productDetails.addedToCart, addedToCart{
                vc.addToCartBtn.setTitle("Remove", for: .normal)
            }else{
                vc.addToCartBtn.setTitle("Add to Cart", for: .normal)
            }
        }
    }
    
    func setupCell(){
        vc.productImageCV.register(UINib(nibName: K.CellIdentifier.Shop.shopProductImageCell, bundle: nil), forCellWithReuseIdentifier: K.CellIdentifier.Shop.shopProductImageCell)
        vc.productImageCV.delegate = vc.self
        vc.productImageCV.dataSource = vc.self
    }
    
    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 = "SHOP".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        self.vc.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
    }
    
    // MARK: - Add To Cart

    func addToCart(shopMasterID : Int){
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["shop_master_id" : shopMasterID]
        
        // 11 - hindi , 12 - english
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Cart.add_cart, method: .post,parameters: params,headers: headers) { [weak self](result : Result<CommonResponseModel, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    Utilities.alert(title: "Error", message: data.message ?? K.ConstantString.unRecognised, viewController: self.vc)
                case 1:
                    Utilities.dismissProgressHUD()
                    self.vc.addToCartBtn.setTitle("Remove", for: .normal)
                    self.vc.toast(msg: data.message ?? "Added to cart", time: 1) {
                        if let productDetails = self.productDetails{
                            CartDataCache.cartListData.append(CartListingDM.ResultData(id: productDetails.id, skuID: productDetails.skuID, productName: productDetails.productName, categoryMasterID: productDetails.categoryMasterID, subCategoryMasterID: productDetails.subCategoryMasterID, productPrice: productDetails.productPrice, remainStockQuantity: productDetails.remainStockQuantity, stockStatus: productDetails.stockStatus, taxValue: productDetails.taxValue, productQuantity: productDetails.remainStockQuantity, shopMasterDetail: productDetails.shopMasterDetail, shopImage: productDetails.shopImage, productFinalPrice: productDetails.productFinalPrice))
                            self.updateCartIcon()
                        }
                    }
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                Utilities.alert(title: "Error", message: error.localizedDescription, viewController: self.vc)
            }
        }
    }
    
    func removeItemFromCart(shopMasterID : Int){
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["shop_master_id" : shopMasterID]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Cart.remove_cart, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<CommonResponseModel>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                    Utilities.alert(title: "Error", message: data.message ?? K.ConstantString.unRecognised, viewController: self.vc)
                case 1:
                    Utilities.dismissProgressHUD()
                    self.vc.addToCartBtn.setTitle("Add to Cart", for: .normal)
                    self.vc.toast(msg: data.message ?? "Removed from cart", time: 1) {
                        self.productDetails?.addedToCart = false
                        if let index = CartDataCache.cartListData.firstIndex(where: {$0.id == self.productDetails?.id}){
                            CartDataCache.cartListData.remove(at: index)
                            self.updateCartIcon()
                        }
                    }
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                Utilities.alert(title: "Error", message: error.localizedDescription, viewController: self.vc)
            }
        }
    }
    
    func updateCartIcon(){
        // Update the badge label with the current cart data
        if let button = cartButton.customView as? UIButton {
            BadgeBarBtn.shared.updateBadge(for: button, with: CartDataCache.cartListData.count.toString())
        }
    }
    
    func getProductDetails(productID : Int){
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["product_id" : productID]
        
        // 11 - hindi , 12 - english
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Shop.shop_product_view, method: .post,parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<[ShopProductsListingDM.ResultData]>, 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: 2)
                    self.vc.scrollView.isHidden = true
                    self.vc.noDataStack.isHidden = false
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data else{return}
                    self.productDetails = data.first
                    self.updateView()
                    self.vc.scrollView.isHidden = false
                    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: 2)
                self.vc.scrollView.isHidden = true
                self.vc.noDataStack.isHidden = false
            }
        }
    }
}
