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

import UIKit
import Alamofire

class AddressListVM{
    
    weak var vc : AddressListVC!
    var couponCodeApplied = String()

    func initView(){
        vc.innerView.addBorderView(width: 1, color: .darkGray)
        self.vc.title = "ADDRESS DETAILS".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        addGradient()
        setupCell()
        getAddressListing()
    }
    
    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)
        
        vc.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
    }
    
    func addBtnGradient(){
        let color1 = #colorLiteral(red: 0.144693464, green: 0.1426281333, blue: 0.6686832905, alpha: 1)
        let color2 = #colorLiteral(red: 0.6901960784, green: 0.2745098039, blue: 0.7568627451, alpha: 1)
        let color3 = #colorLiteral(red: 0.968627451, green: 0.4196078431, blue: 0.1098039216, alpha: 1)
        let color4 = #colorLiteral(red: 0.968627451, green: 0.7882352941, blue: 0.1294117647, alpha: 1)
        vc.useSelectedAddBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.addNewAddressBtn.applyGradient(colors: [color3, color4], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
        vc.useSelectedAddBtn.roundCorner()
        vc.addNewAddressBtn.roundCorner()
    }
    
    func setupCell(){
        vc.tableView.register(UINib(nibName: K.CellIdentifier.Cart.addressCell, bundle: nil), forCellReuseIdentifier: K.CellIdentifier.Cart.addressCell)
        vc.tableView.delegate = vc.self
        vc.tableView.dataSource = vc.self
    }
    
    // MARK: - Get Address list
    
    func getAddressListing(){
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Address.parent_address_listing, method: .get,headers: headers) { [weak self](result : Result<BaseResponseModel<[AddressListDM]>, 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.checkForNoData()
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data else{return}
                    CartDataCache.addressData = data
                    if CartDataCache.addressData.count != 0{
                        CartDataCache.addressData[0].isDefault = true
                        CartDataCache.addressData[0].isAnimating = true
                    }
                    self.vc.tableView.reloadData()
                    self.checkForNoData()
                    if let pincode = CartDataCache.addressData.first?.pincode , let id = CartDataCache.addressData.first?.id{
                        checkEstimatedDeliveryData(pinCode: pincode, id: id)
                    }
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    self?.checkForNoData()
                    return
                }
                Utilities.dismissProgressHUD()
                checkForNoData()
                Utilities.alertWithBtnCompletion(title: "Error", msgBody: error.localizedDescription, okBtnStr: "Retry?", vc: self.vc) { isDone in
                    if isDone{
                        self.getAddressListing()
                    }
                }
            }
        }
    }
    
    func checkForNoData(){
        if CartDataCache.addressData.count == 0{
            vc.useSelectedAddBtn.isHidden = true
            vc.noDataStack.isHidden = false
        }else{
            vc.useSelectedAddBtn.isHidden = false
            vc.noDataStack.isHidden = true
        }
    }
    
    func checkEstimatedDeliveryData(pinCode : String, id : Int){
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["pincode" : pinCode]
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Address.pincode_serviceability_check_edd, method: .post, parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<CheckEddDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    if let index = CartDataCache.addressData.firstIndex(where: {$0.id == id}){
                        CartDataCache.addressData[index].eddDate = data.edd
                        CartDataCache.addressData[index].isAnimating = false
                        self.vc.tableView.reloadData()
                    }
                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 createOrder(addressID : Int,couponCode : String?){
        var productIDs = [Int]()
        
        for i in CartDataCache.cartListData{
            if let id = i.id{
                productIDs.append(id)
            }
        }
        Utilities.startProgressHUD()
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["product_ids" : productIDs,
                                   "address_id" : addressID,
                                   "coupon_code" : couponCode ?? ""]
        struct URLResp : Codable {
            var url : String?
        }
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Cart.create_new_order, method: .post, parameters: params,headers: headers) { [weak self](result : Result<BaseResponseModel<URLResp>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                switch data.success{
                case 0:
                    /*
                     Error
                     */
                    Utilities.dismissProgressHUD()
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data else{return}
                    let sb = UIStoryboard(name: K.StoryBoard.address, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Address.paymentWebViewVC) as! PaymentWebViewVC
                    vcPush.url = data.url
                    vcPush.modalTransitionStyle = .crossDissolve
                    vcPush.modalPresentationStyle = .fullScreen
                    self.vc.navigationController?.pushViewController(vcPush, animated: true)
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                Utilities.alertWithBtnCancelCompletion(title: "Error", msgBody: error.localizedDescription, okBtnStr: "Retry?", vc: self.vc) { isDone in
                    if isDone{
                        self.createOrder(addressID: addressID, couponCode: couponCode)
                    }
                }
            }
        }
    }
}
