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

import UIKit
import Alamofire

class VerifyAddressPincodeVC: UIViewController {

    @IBOutlet weak var pinCodeTF: TextFieldShadow!
    @IBOutlet weak var proceedBtn: LocalisedElementsButton!
    @IBOutlet weak var pincodeServieable: LocalisedElementsLabel!
    
    var verifyPincodeData : CheckEddDM.ResultData?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addGradient()
        self.pinCodeTF.roundCorner()
        self.title = "ADDRESS DETAILS".localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        pinCodeTF.delegate = self
    }
    
    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)
    }

    @IBAction func proceedBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addShopCount(postID: 0)
        guard let tf = pinCodeTF.text else{return}
        if sender.titleLabel?.text == "CHECK NOW"{
            if tf.count < 6{
                Utilities.alertWithBtn(title: "", msgBody: "Please enter 6 digit pincode.", okBtnStr: "OK", vc: self)
                return
            }
            
            if tf == "000000"{
                self.pincodeServieable.text = "Pincode is not valid."
                proceedBtn.setTitle("CHECK NOW", for: .normal)
                return
            }
            
            //check if user is checking for same pincode
            if let verifyPincodeData{
                if tf == verifyPincodeData.lmPincode{
                    checkServiceAble()
                    return
                }
            }
            
            checkEstimatedDeliveryData(pinCode: tf)
        } else{
            let sb = UIStoryboard(name: K.StoryBoard.address, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Address.addNewAddressVC) as! AddNewAddressVC
            vcPush.vm.pincode = tf
            self.navigationController?.pushViewController(vcPush, animated: true)
        }
    }
    
    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)
        
        self.view.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
    }
    
    func checkEstimatedDeliveryData(pinCode : String){
        Utilities.startProgressHUD(msg: "Checking Pincode..")
        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()
                    self.pincodeServieable.text = data.message ?? "Pincode not serviceable."
                    proceedBtn.setTitle("CHECK NOW", for: .normal)
                case 1:
                    Utilities.dismissProgressHUD()
                    guard let data = data.data?.result else{return}
                    self.verifyPincodeData = data
                    checkServiceAble()
                default:
                    Utilities.dismissProgressHUD()
                    break
                }
            case .failure(let error):
                guard let self else{
                    Utilities.dismissProgressHUD()
                    return
                }
                Utilities.dismissProgressHUD()
                self.toast(msg: error.localizedDescription, time: 1.5)
            }
        }
    }
    
    func checkServiceAble(){
        guard let data = self.verifyPincodeData else{
            self.pincodeServieable.text = "Pincode not serviceable."
            proceedBtn.setTitle("CHECK NOW", for: .normal)
            return
        }
        proceedBtn.setTitle("PROCEED", for: .normal)
        self.pincodeServieable.text = "Pincode Servicable." + "\n" + "Expected delivery by " + (data.edd ?? "123456")
    }
}

extension VerifyAddressPincodeVC : UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        // Check if user is deleting text so hide pincode servicable text
        if string.count == 0 && range.length > 0 {
            self.pincodeServieable.text = ""
            self.proceedBtn.setTitle("CHECK NOW", for: .normal)
            // Back pressed
            return true
        }
        
        //Pincode should be only number
        if !string.onlyNumber(){return false}
        
        // pincode should be max 6 characters in length
        return ValidatorClass.sharedInstanec.limitCharacter(length: 6,textField, shouldChangeCharactersIn: range, replacementString: string)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("Return")
        return true
    }
}
