//
//  MyOrdersVM.swift
//  WOKA
//
//  Created by MacBook Pro on 30/07/24.
//

import UIKit
import Alamofire

class MyOrdersVM{
    
    weak var vc : MyOrdersVC!
    var cartButton: UIBarButtonItem!
    var pageNo = 1
    var stopFetch = false
    var orderData = [OrderListingDM.Datum]()
    var footerView = UIView()

    let refreshControl = UIRefreshControl()
    let feedbackGenerator = UIImpactFeedbackGenerator(style: .light)
    func initView(){
        
        vc.title = "MY ORDERS".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vc.tableView.indicatorStyle = .black
        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)
        
        cartButton = BadgeBarBtn.shared.setupCartButton(target: self, action: #selector(self.cartButtonTapped))
        self.vc.navigationItem.rightBarButtonItem = cartButton
        
        //check if cart is not fetched
        if !CartDataCache.isFetched{
            CartDataCache.shareInstance.getCartList(vc: self.vc) { [weak self] isDone in
                guard let self else{return}
                if isDone{
                    if let button = cartButton.customView as? UIButton {
                        BadgeBarBtn.shared.updateBadge(for: button, with: CartDataCache.cartListData.count.toString())
                    }
                }
            }
        }
        
        // Set up the footer view with a button
        let footerView = createFooterView()
        vc.tableView.tableFooterView = footerView
        self.toggleFooterView(show: false)
        setupCell()
        Utilities.startProgressHUD()
        getOrders()
    }
    
    func setupCell(){
        vc.tableView.register(UINib(nibName: K.CellIdentifier.SideBarNav.myOrderCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.SideBarNav.myOrderCell)
        vc.tableView.delegate = vc.self
        vc.tableView.dataSource = vc.self
    }
    
    @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)
    }
    
    @objc func refresh(_ sender: AnyObject) {
        pageNo = 1
        self.getOrders()
    }
    
    // MARK: - Get MyORders
    
    func getOrders(){
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi",
                                     "access-token": AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["limit" : "10"]
        let url = "\(APIEndPoints.SideBarNav.order_listing )?page=\(pageNo)"
        NetworkManager.shareInstance.apiRequest(url: url, method: .post, parameters: params,headers : headers) { [weak self](result : Result<BaseResponseModel<OrderListingDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0:
                    guard let self else{return}
                    Utilities.dismissProgressHUD()
                    refreshControl.endRefreshing()
                    vc.noDataStack.isHidden = false
                case 1:
                    guard let self, let totalCount = data.data?.result?.total , let data = data.data?.result?.data else{
                        Utilities.dismissProgressHUD()
                        self?.refreshControl.endRefreshing()
                        self?.vc.noDataStack.isHidden = false
                        return
                    }
                    vc.noDataStack.isHidden = true

                    if refreshControl.isRefreshing{
                        self.orderData.removeAll()
                    }
                    self.orderData.append(contentsOf: data)
                    if self.orderData.count == totalCount{
                        self.toggleFooterView(show: false)
                    }else{
                        self.toggleFooterView(show: true)
                    }
                    self.vc.tableView.reloadData()
                    Utilities.dismissProgressHUD()
                    refreshControl.endRefreshing()
                    feedbackGenerator.impactOccurred()
                default:
                    break
                }
            case .failure(let error):
                guard let self else{return}
                Utilities.dismissProgressHUD()
                refreshControl.endRefreshing()
                vc.noDataStack.isHidden = false
                print(error)
            }
        }
    }
    
    // Toggle footer view visibility
    func toggleFooterView(show: Bool) {
        if show {
            vc.tableView.tableFooterView = footerView
        } else {
            vc.tableView.tableFooterView = nil
        }
    }
    
    func createFooterView() -> UIView {
        // Create a UIView for the footer
        footerView = UIView(frame: CGRect(x: 0, y: 0, width: vc.view.frame.width, height: 60))
        footerView.backgroundColor = .clear // You can set a background color if you want
        
        // Create a UIButton
        let button = UIButton(type: .system)
        button.setTitle("Load More", for: .normal)
        button.titleLabel?.font = FontCustom.shareInstance.customFont(fontName: .Exo2_Bold, size: 16)
        button.backgroundColor = UIColor.appColor(.TextDarkBlue)
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 25
        button.frame = CGRect(x: 0, y: 0, width: vc.view.frame.width, height: 50)
        
        // Add action to the button
        button.addTarget(self, action: #selector(footerButtonTapped), for: .touchUpInside)
        
        button.translatesAutoresizingMaskIntoConstraints = false

        // Add the button to the footer view
        footerView.addSubview(button)
        
        // Set up Auto Layout constraints
        NSLayoutConstraint.activate([
            // Center the button horizontally in the footer view
            button.centerXAnchor.constraint(equalTo: footerView.centerXAnchor),
            // Center the button vertically in the footer view
            button.centerYAnchor.constraint(equalTo: footerView.centerYAnchor),
            // Set the button's width with 50 points padding from each side
//            button.leadingAnchor.constraint(equalTo: footerView.leadingAnchor, constant: 50),
//            button.trailingAnchor.constraint(equalTo: footerView.trailingAnchor, constant: -50),
            // Set the button's height
            button.heightAnchor.constraint(equalToConstant: 50),
            button.widthAnchor.constraint(equalToConstant: 160)
        ])
        
        return footerView
    }
    
    @objc func footerButtonTapped() {
        Utilities.startProgressHUD()
        pageNo += 1
        getOrders()
    }
}
