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

import UIKit

class CartListVC: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var totalPrice: LocalisedElementsLabel!
    @IBOutlet weak var noDataStack: UIStackView!
    @IBOutlet weak var checkoutBtn: LocalisedElementsButton!
    var vm = CartListVM()
    static let shareInstance = CartListVC()
    
    // MARK: - Life Cycle

    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        self.navigationController?.setColor(color: .white)

    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        if self.isMovingFromParent {
            // Back button was pressed
            PersistentStorage.shared.addOthersCount()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        // Customize the navigation bar's appearance
        self.navigationController?.setColor(color: .black)
    }

    // MARK: - Tap Handler

    @IBAction func checkoutBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addShopCount(postID: 0)
        
        if AuthFunc.shareInstance.getUserType() == 1{ // Kids cannot purchase goods
//            Utilities.alertWithBtn(title: "", msgBody: "Children cannot purchase this product. Please contact your Guardian.", okBtnStr: "OK", vc: self)
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            vcPush.contentLabel = "Children cannot purchase this product. Please contact your Guardian."
            vcPush.mainTitleText = "Purchase"
            vcPush.yesBtnText = "OK"
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }
        let sb = UIStoryboard(name: K.StoryBoard.cart, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Cart.cartPaymentOptionsVC) as! CartPaymentOptionsVC
//        vcPush.vm.cartListData = vm.cartListData
        vcPush.vm.cartTotalPrice = vm.totalAmount
        self.navigationController?.pushViewController(vcPush, animated: true)
    }
}

// MARK: - TableView DataSource , Delegates

extension CartListVC : TableViewSRC{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return CartDataCache.cartListData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.Cart.cartListCell) as! CartListCell
        let data = CartDataCache.cartListData[indexPath.row]
        cell.setData(data: data)
        cell.btnTapped = { [weak self] () -> Void in
            guard let self else{return}
            handleMoveToTrash(indexPath: indexPath.row)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView,trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?{

        // Trash action
        let trash = UIContextualAction(style: .destructive,title: "Delete".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)) { [weak self] (action, view, completionHandler) in
            self?.handleMoveToTrash(indexPath: indexPath.row)
            completionHandler(true)
        }
        trash.backgroundColor = UIColor.red
        trash.image = UIImage(named: "DeleteIcon")?.withTintColor(UIColor.white)

        tableView.swipeGestureFont(font: FontCustom.shareInstance.customFont(fontName: .Exo2_Medium, size: 14))

        let configuration = UISwipeActionsConfiguration(actions: [trash])
        // If you do not want an action to run with a full swipe
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    }

    private func handleMoveToTrash(indexPath : Int) {
        if let postID = CartDataCache.cartListData[indexPath].id{
            PersistentStorage.shared.addShopCount(postID: postID)
        }
        let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
        let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.yesNoAlertVC) as! YesNoAlertVC
        vcPush.mainTitleText = "Alert!".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vcPush.contentLabel = "Are you sure you want to remove item from cart?".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vcPush.yesBtnText = "Remove".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vcPush.noBtnText = "Cancel".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        vcPush.onDoneBlock = { [weak self] mode in
            switch mode{
            case .yes:
                guard let self else{return}
                if let postID = CartDataCache.cartListData[indexPath].id{
                    PersistentStorage.shared.addShopCount(postID: postID)
                }
                if let shopMasterID = CartDataCache.cartListData[indexPath].id{
                    vm.removeItemFromCart(shopMasterID: shopMasterID, index: indexPath)
                }
            case .no:
                if let postID = CartDataCache.cartListData[indexPath].id{
                    PersistentStorage.shared.addShopCount(postID: postID)
                }
            }
        }
        vcPush.modalPresentationStyle = .overCurrentContext
        vcPush.modalTransitionStyle = .crossDissolve
        self.present(vcPush, animated: true)
        print(indexPath)
    }
}
