//
//  AddressListVC.swift
//  WOKA
//
//  Created by MacBook Pro on 25/07/24.
//

import UIKit

class AddressListVC: UIViewController {

    @IBOutlet weak var innerView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var useSelectedAddBtn : LocalisedElementsButton!
    @IBOutlet weak var addNewAddressBtn : LocalisedElementsButton!
    @IBOutlet weak var noDataStack: UIStackView!
    
    var vm = AddressListVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()

        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    override func viewDidLayoutSubviews() {
        vm.addBtnGradient()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        self.navigationController?.setColor(color: .white)
        // handle data change
        self.vm.checkForNoData()
        self.tableView.reloadData()
    }
    
    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)
    }

    @IBAction func btnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addShopCount(postID: 0)

        switch sender{
        case useSelectedAddBtn:
            if CartDataCache.addressData.count == 0{
                self.toast(msg: "Please add address", time: 1.5)
                return
            }
            if let addressID = CartDataCache.addressData.filter({$0.isDefault == true}).first?.id{
                vm.createOrder(addressID: addressID, couponCode: vm.couponCodeApplied)
            }
        case addNewAddressBtn:
            let sb = UIStoryboard(name: K.StoryBoard.address, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Address.verifyAddressPincodeVC) as! VerifyAddressPincodeVC
            self.navigationController?.pushViewController(vcPush, animated: true)
        default:
            break
        }
    }
}

// MARK: - TableView DataSource , Delegates

extension AddressListVC : TableViewSRC{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return CartDataCache.addressData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.CellIdentifier.Cart.addressCell) as! AddressCell
        let data = CartDataCache.addressData[indexPath.row]
        cell.setData(data: data)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Resetting the Radio clicks
        for index in CartDataCache.addressData.indices {
            CartDataCache.addressData[index].isDefault = false
        }
        
        PersistentStorage.shared.addShopCount(postID: 0)
        
        //
        if CartDataCache.addressData[indexPath.row].eddDate == nil || CartDataCache.addressData[indexPath.row].eddDate == ""{
            if let pincode = CartDataCache.addressData[indexPath.row].pincode, let id = CartDataCache.addressData[indexPath.row].id{
                // check if array has same pincode and edd is there
                if let alreadyPincodePresent = CartDataCache.addressData.firstIndex(where: {$0.pincode == pincode && $0.eddDate != nil}){
                    CartDataCache.addressData[indexPath.row].eddDate = CartDataCache.addressData[alreadyPincodePresent].eddDate
                }else{
                    // else if not present fetch it again
                    CartDataCache.addressData[indexPath.row].isAnimating = true
                    vm.checkEstimatedDeliveryData(pinCode: pincode, id: id)
                }
            }
        }
        
        CartDataCache.addressData[indexPath.row].isDefault = true
        tableView.reloadData(with: .fade)
    }
}

extension UITableView {
    func reloadData(with animation: UITableView.RowAnimation) {
        reloadSections(IndexSet(integersIn: 0..<numberOfSections), with: animation)
    }
}
