//
//  AddNewAddressVM.swift
//  WOKA
//
//  Created by MacBook Pro on 29/07/24.
//

import UIKit
import Alamofire

class AddNewAddressVM{
    
    weak var vc : AddNewAddressVC!
    var pincode = String()

    func initView(){
        vc.title = "ADDRESS DETAILS".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        addGradient()
        
        vc.enterAddressNAmeTF.delegate = self.vc
        vc.addressLine1TF.delegate = self.vc
        vc.addressLine2TF.delegate = self.vc
        vc.cityTF.delegate = self.vc
        vc.stateTF.delegate = self.vc
        vc.countryTF.delegate = self.vc
        vc.phoneNumberTF.delegate = self.vc
        
        vc.enterAddressNAmeTF.roundCorner()
        vc.addressLine1TF.roundCorner()
        vc.addressLine2TF.roundCorner()
        vc.cityTF.roundCorner()
        vc.stateTF.roundCorner()
        vc.countryTF.roundCorner()
        vc.phoneNumberTF.roundCorner()
        vc.pinCodeTF.roundCorner()
        vc.pinCodeTF.text = pincode
    }
    
    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 addAddress(){
        Utilities.startProgressHUD()
        let address = (vc.addressLine1TF.text ?? "") + ", " + (vc.addressLine2TF.text ?? "")
        let headers : HTTPHeaders = ["access-token" : AuthFunc.shareInstance.getAccessToken()]
        let params : Parameters = ["address_name" : vc.enterAddressNAmeTF.text!,
                                   "address" : address,
                                   "city" : vc.cityTF.text!,
                                   "state" : vc.stateTF.text!,
                                   "pincode" : vc.pinCodeTF.text!,
                                   "mobile_number" : vc.phoneNumberTF.text!]
        
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.Address.add_parent_address, method: .post, parameters: params,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()
                case 1:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Address Added", time: 2) {
                        guard let data = data.data else{return}
                        
                        CartDataCache.addressData.append(data)
                        
                        //set the newly added address as default
                        if let updateDefaultIndex = CartDataCache.addressData.lastIndex(where: {$0.id == data.id}){
                            for index in CartDataCache.addressData.indices {
                                CartDataCache.addressData[index].isDefault = false
                            }
                            CartDataCache.addressData[updateDefaultIndex].isDefault = true
                        }
                        
                        guard let navigationController = self.vc.navigationController else {
                            print("Not in a navigation controller")
                            return
                        }

                        if let targetController = navigationController.viewControllers.first(where: { $0 is AddressListVC }) {
                            navigationController.popToViewController(targetController, animated: true)
                        } else {
                            print("Target view controller not found in the navigation stack")
                        }
                    }
                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)
            }
        }
    }
}
