//  TabBarVC
//
//  Created by MacBook Pro on 14/05/24.
//


import UIKit
import Alamofire

class TabBarVC: UITabBarController {
    
    var upperLineView: UIView!
    
    let spacing: CGFloat = 12
    var customTabBarView = UIView(frame: .zero)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.title = ""
        customizeTabBarItemFont()
        updateText()
        self.setupTabBarUI()
        self.addCustomTabBarView()
        NotificationCenter.default.addObserver(self, selector: #selector(languageDidChange), name: .languageDidChange, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(linkPush), name: .linkPush, object: nil)

        customizeTabBarItemIconSize()
        
        self.navigationController?.setColor(color: .black)

    }
    
    deinit{
        NotificationCenter.default.removeObserver(self, name: .languageDidChange, object: nil)
        NotificationCenter.default.removeObserver(self, name: .linkPush, object: nil)
    }
    
    @objc func linkPush(_ notification: NSNotification){
        if let type = notification.userInfo?["type"] as? LinkTypeEnum {
            Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in
                switch type{
                case .about:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.aboutUsVc) as! AboutUsVc
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .faq:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.faqVC) as! FaqVC
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .support:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.contactSupportVC) as! ContactSupportVC
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .profile:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.profileVC) as! ProfileVC
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .addChild:
                    let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.userDetailsRegisterVC) as! UserDetailsRegisterVC
                    vcPush.vm.createChildAccount = true
                    AuthFunc.shareInstance.regData.email = AuthFunc.shareInstance.userData?.email
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .order:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.myOrdersVC) as! MyOrdersVC
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .deactivate:
                    let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.yesNoAlertVC) as! YesNoAlertVC
                    vcPush.mainTitleText = "Deactivate WOKA Account"
                    vcPush.contentLabel = "By clicking the button below, your account will be deactivated. Your data will be erased after one month."
                    vcPush.yesBtnText = "Deactivate"
                    vcPush.noBtnText = "Cancel"
                    vcPush.onDoneBlock = { [unowned self] mode in
                        switch mode{
                        case .yes:
                            //If user clicked nav him to login screen. Call the api.
                            PersistentStorage.shared.addOthersCount()
                            deactivateAccount()
                            print("Yes")
                        case .no:
                            PersistentStorage.shared.addOthersCount()
                            print("no")
                        }
                    }
                    vcPush.modalPresentationStyle = .overCurrentContext
                    vcPush.modalTransitionStyle = .crossDissolve
                    self.present(vcPush, animated: true)
                case .termsCondition:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.webViewVC) as! WebViewVC
                    vcPush.url = APIEndPoints.Links.termsAndCondition
                    vcPush.pageTitle = "Terms & Condition"
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .privacyPolicy:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.webViewVC) as! WebViewVC
                    vcPush.url = APIEndPoints.Links.privacyPolicy
                    vcPush.pageTitle = "Privacy Policy"
                    self.navigationController?.pushViewController(vcPush, animated: true)
                case .disclaimer:
                    let sb = UIStoryboard(name: K.StoryBoard.sideBarNav, bundle: nil)
                    let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.SideBarNav.webViewVC) as! WebViewVC
                    vcPush.pageTitle = "Disclaimer"
                    vcPush.textContent = .disclaimer
                    self.navigationController?.pushViewController(vcPush, animated: true)
                }
            }
        }
    }
    
    @objc private func languageDidChange() {
        updateText()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if hasTopNotch{
            tabBar.frame.size.height = 90
            tabBar.frame.origin.y = view.frame.height - 90
        }else{
            tabBar.frame.size.height = 60
            tabBar.frame.origin.y = view.frame.height - 60
        }
        
    }
    
    func updateText(){
        guard let tabItems = self.tabBar.items else{return}
        tabItems[0].title = tabItems[0].title?.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        tabItems[1].title = tabItems[1].title?.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
        tabItems[2].title = tabItems[2].title?.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
    }
    
    func customizeTabBarItemIconSize() {
        // Get a reference to the tab bar controller
        if let tabBarController = self.tabBarController {
            // Loop through each tab bar item
            for item in tabBarController.tabBar.items! {
                // Adjust the image insets to increase the icon size
                item.imageInsets = UIEdgeInsets(top: 2, left: -5, bottom: -8, right: -5)
                item.titlePositionAdjustment.vertical = CGFloat(8)
            }
        }
    }
    
    // function to set tab bar item font
    func customizeTabBarItemFont() {
        // Set the font attributes
        let attributes = [NSAttributedString.Key.font: FontCustom.shareInstance.customFont(fontName: .Exo2_Bold, size: 13)]
        
        // Apply the attributes to the appearance proxy of UITabBarItem
        UITabBarItem.appearance().setTitleTextAttributes(attributes, for: .normal)
    }
    
    // MARK: - Deactivate Account API Call

    func deactivateAccount(){
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi",
                                     "access-token" : AuthFunc.shareInstance.getAccessToken()]
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.SideBarNav.user_deactivate_account, method: .get,headers: headers) {(result : Result<BaseResponseModel<UserEmailVerifyDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                switch data.success{
                case 0: // some error
                    Utilities.dismissProgressHUD()
                    self.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    self.toast(msg: data.message ?? "Deactivated Account Successfully.", time: 2) {
                        AuthFunc.shareInstance.logout()
                        UIApplication.setRootView(LoginNavVC.instantiate(from: .AuthenticationSB))
                    }
                default:
                    Utilities.dismissProgressHUD()
                    self.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    // MARK: Private methods
    
    private func setupCustomTabBarFrame() {
        let height = self.view.safeAreaInsets.bottom + 64
        
        var tabFrame = self.tabBar.frame
        tabFrame.size.height = height
        tabFrame.origin.y = self.view.frame.size.height - height
        
        self.tabBar.frame = tabFrame
        self.tabBar.setNeedsLayout()
        self.tabBar.layoutIfNeeded()
        customTabBarView.frame = tabBar.frame
    }
    
    private func setupTabBarUI() {
        // Setup your colors and corner radius
        self.tabBar.backgroundColor = UIColor.white
        self.tabBar.layer.cornerRadius = 15
        self.tabBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        self.tabBar.backgroundColor = .white
        self.tabBar.tintColor = #colorLiteral(red: 0.0349480696, green: 0.0643344149, blue: 0.4407724142, alpha: 1)
        self.tabBar.unselectedItemTintColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
        
        // Remove the line
        if #available(iOS 13.0, *) {
            let appearance = self.tabBar.standardAppearance
            appearance.shadowImage = nil
            appearance.shadowColor = nil
            self.tabBar.standardAppearance = appearance
        } else {
            self.tabBar.shadowImage = UIImage()
            self.tabBar.backgroundImage = UIImage()
        }
    }
    
    private func addCustomTabBarView() {
        self.customTabBarView.frame = tabBar.frame
        
        self.customTabBarView.backgroundColor = .white
        self.customTabBarView.layer.cornerRadius = 30
        self.customTabBarView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        
        self.customTabBarView.layer.masksToBounds = false
        self.customTabBarView.layer.shadowColor = UIColor.red.withAlphaComponent(0.8).cgColor
        self.customTabBarView.layer.shadowOffset = CGSize(width: -4, height: -6)
        self.customTabBarView.layer.shadowOpacity = 0.5
        self.customTabBarView.layer.shadowRadius = 20
        
        self.view.addSubview(customTabBarView)
        self.view.bringSubviewToFront(self.tabBar)
    }
}

extension TabBarVC: UITabBarControllerDelegate {
    
    // Implement the tabBarController(_:didSelect:) method to handle tab changes
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        // This method will be called whenever a tab is selected
        // Do something based on the selected index
        print("Selected tab index: \(tabBarController.selectedIndex)")
        PersistentStorage.shared.addOthersCount()
        
        if tabBarController.selectedIndex == 1{
            
        }
    }
    
    // Implement the tabBarController(_:shouldSelect:) method to control tab selection
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        if viewController == tabBarController.viewControllers?[1] {
            PersistentStorage.shared.addOthersCount()
            
            let sb = UIStoryboard(name: "Home", bundle: nil)
            let vc = sb.instantiateViewController(withIdentifier: "ExploreWokaVC") as! ExploreWokaVC
            vc.modalPresentationStyle = .overCurrentContext
            vc.modalTransitionStyle = .crossDissolve
            present(vc, animated: true, completion: nil)
            return false
        }
        // Return false to prevent tab selection
        return true
    }
}


var hasTopNotch: Bool {
    if #available(iOS 11.0, tvOS 11.0, *) {
        return UIApplication.shared.keyWindowInConnectedScenes?.safeAreaInsets.top ?? 0 > 20
    }
    return false
}
