//
//  CartListVM.swift
//  WOKA
//
//  Created by MacBook Pro on 23/07/24.
//

import UIKit
import Alamofire

class CartListVM{
    
    weak var vc : CartListVC!
//    var cartListData = [CartListingDM.ResultData]()
    
    var totalAmount = 0.0 {
        didSet{
            vc.totalPrice.text = K.ConstantString.rupeeSign + " " + totalAmount.toString()
        }
    }
    
    let refreshControl = UIRefreshControl()
    let feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
    
    func initView(){
        setupCell()
        Utilities.startProgressHUD()
        getCartList()
        addGradient()
        
        vc.tableView.indicatorStyle = .white
        refreshControl.attributedTitle = NSAttributedString(string: "Refreshing...",attributes: [.foregroundColor: UIColor.appColor(.TextDarkBlue)!])
        refreshControl.tintColor = UIColor.appColor(.TextDarkBlue)!
        refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
        vc.tableView.addSubview(refreshControl)
    }
    
    @objc func refresh(_ sender: AnyObject) {
        self.getCartList()
    }
    
    func addGradient(){
        self.vc.title = "MY CART".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        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)
        
        vc.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
    }
    
    func setupCell(){
        vc.tableView.register(UINib(nibName: K.CellIdentifier.Cart.cartListCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.Cart.cartListCell)
        vc.tableView.delegate = vc.self
        vc.tableView.dataSource = vc.self
    }
    // MARK: - Get SuperCategory
    
    func getCartList(){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Cart.cart_listing, method: .get,headers: headers) { [weak self](result : Result<BaseResponseModel<CartListingDM>, 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.refreshControl.endRefreshing()
                    self.checkCount()
                case 1:
                    Utilities.dismissProgressHUD()
                    self.refreshControl.endRefreshing()
                    totalAmount = data.data?.totalAmount ?? 0.0
                    
                    guard let data = data.data?.result else{return}
                    CartDataCache.cartListData = data
                    self.vc.tableView.reloadData()
                    feedbackGenerator.impactOccurred()
                    self.checkCount()
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    self?.refreshControl.endRefreshing()
                    return
                }
                Utilities.dismissProgressHUD()
                self.refreshControl.endRefreshing()
                self.checkCount()
                vc.toast(msg: error.localizedDescription , time: K.ConstantString.errorTime)
            }
        }
    }
    
    func checkCount(){
        if CartDataCache.cartListData.count == 0 {
            self.vc.noDataStack.isHidden = false
            self.vc.checkoutBtn.isEnabled = false
            self.vc.checkoutBtn.backgroundColor = #colorLiteral(red: 0.03529411765, green: 0, blue: 0.3647058824, alpha: 1).withAlphaComponent(0.7)
        } else{
            self.vc.noDataStack.isHidden = true
            self.vc.checkoutBtn.isEnabled = true
            self.vc.checkoutBtn.backgroundColor = #colorLiteral(red: 0.03529411765, green: 0, blue: 0.3647058824, alpha: 1)
        }
    }
    
    func removeItemFromCart(shopMasterID : Int, index : 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.alertWithBtnCompletion(title: "Error", msgBody: data.message ?? K.ConstantString.unRecognised, okBtnStr: "Retry?", vc: self.vc) { isDone in
                        if isDone{
                            self.getCartList()
                        }
                    }
                case 1:
                    Utilities.dismissProgressHUD()
                    self.totalAmount = self.totalAmount - (CartDataCache.cartListData[index].productFinalPrice ?? 0.0)
                    CartDataCache.cartListData.remove(at: index)
                    self.vc.tableView.reloadData()
                    self.checkCount()
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                self.refreshControl.endRefreshing()
                Utilities.alertWithBtnCompletion(title: "Error", msgBody: error.localizedDescription, okBtnStr: "Retry?", vc: self.vc) { isDone in
                    if isDone{
                        self.getCartList()
                    }
                }
            }
        }
    }
}
