//
//  ContactSupportVM.swift
//  WOKA
//
//  Created by Bilal on 05/06/2024.
//

import UIKit
import Alamofire

class ContactSupportVM{
    
    weak var vc : ContactSupportVC!
    let dropDownModule = DropDown()
    var dataSource = [String]()
    
    func initView(){
        let color1 = #colorLiteral(red: 0.7294117647, green: 0.7529411765, blue: 0.3803921569, alpha: 1)
        let color2 = #colorLiteral(red: 0.1843137255, green: 0.2156862745, blue: 0.0431372549, alpha: 1)
        vc.view.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.supportGirlImage.roundCorner()

        userTypeManipulations()

        
        vc.emailTF.roundCorner()
        vc.nameTF.roundCorner()
        vc.nameTF.delegate = self.vc
        vc.emailTF.delegate = self.vc
        vc.messageTextView.delegate = self.vc
        
        
        let color3 = #colorLiteral(red: 0.968627451, green: 0.7882352941, blue: 0.1294117647, alpha: 1)
        let color4 = #colorLiteral(red: 0.968627451, green: 0.4196078431, blue: 0.1098039216, alpha: 1)
        vc.submitBtn.applyGradient(colors: [color3, color4], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.submitBtn.roundCorner()
        
        vc.subjectStack.roundCorner()
        
        vc.messageTextView.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        vc.messageTextView.applyInnerShadow(radius: 15)
        vc.subjectStack.applyInnerShadow(radius: vc.subjectStack.frame.height / 2)

//        vc.nameTF.addRightButton(title: "", tintColor: UIColor.red, btnImage: UIImage(systemName: "exclamationmark.circle.fill"), target: self, action: #selector(errorName))
//        vc.nameTF.rightView?.isHidden = true
//        
//        vc.emailTF.addRightButton(title: "", tintColor: UIColor.red, btnImage: UIImage(systemName: "exclamationmark.circle.fill"), target: self, action: #selector(errorEmail))
//        vc.emailTF.rightView?.isHidden = true
        
        dataSource = ["Query" , "Complaint", "Suggestion", "Other"]
        initDropDown()
        
        vc.bottomArrow.addTapGesture {
            PersistentStorage.shared.addOthersCount()
            self.dropDownModule.show()
        }
        
        vc.subjectLabel.addTapGesture {
            PersistentStorage.shared.addOthersCount()
            self.dropDownModule.show()
        }
        
    }
    
//    @objc func errorName(){
//        let errorView = errorViews.object(forKey: vc.nameTF)
//        if let errorView = errorView {
//            errorView.isHidden.toggle()
//        }
//    }
//    
//    @objc func errorEmail(){
//        let errorView = errorViews.object(forKey: vc.emailTF)
//        if let errorView = errorView {
//            errorView.isHidden.toggle()
//        }
//    }
    
    private func userTypeManipulations(){
        if let userType = AuthFunc.shareInstance.getUserType(){  // 1- kid , 2 - guardian , 3 - guest
            switch userType{
            case 1: // if th user is child dont let him contact support
                vc.subjectMainStack.isHidden = true
                vc.nameStack.isHidden = true
                vc.emailStack.isHidden = true
                vc.messageStack.isHidden = true
                vc.submitBtn.isHidden = true
                vc.assistanceLabel.isHidden = false
                return
            case 2:
                break
            case 3:
                vc.nameStack.isHidden = false
                vc.emailStack.isHidden = false
            default:
                break
            }
        }
    }
    
    func contactSupportApiCall(){
        let params: Parameters = [
            "user_id": AuthFunc.shareInstance.getUserID(),
            "subject": vc.subjectLabel.text!,
            "message": vc.messageTextView.text!,
        ]
        
        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_queries_store, method: .post ,parameters: params,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.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Message Sent", time: 1.5) {
                        self.vc.navigationController?.popViewController(animated: true)
                    }
                default:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    func guestContactSupportApiCall(){
        let params: Parameters = [
            "name": vc.nameTF.text!,
            "email_id": vc.emailTF.text!,
            "subject": vc.subjectLabel.text!,
            "message": vc.messageTextView.text!,
        ]
        
        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi"]

        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.SideBarNav.guest_queries_store, method: .post ,parameters: params,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.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                case 1: // Success
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Message Sent", time: 1.5) {
                        self.vc.navigationController?.popViewController(animated: true)
                    }
                default:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: K.ConstantString.unRecognised , time: 1)
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription , time: 2)
            }
        }
    }
    
    // this func will initialize the dropdown menu
    func initDropDown(){
        dropDownModule.anchorView = vc.subjectStack
        dropDownModule.dataSource = dataSource
        dropDownModule.cornerRadius = 10
        dropDownModule.bottomOffset = CGPoint(x: 0, y:(dropDownModule.anchorView?.plainView.bounds.height)!)
        dropDownModule.topOffset = CGPoint(x: 0, y:-(dropDownModule.anchorView?.plainView.bounds.height)!)
        dropDownModule.direction = .bottom
        dropDownModule.textFont = FontCustom.shareInstance.customFont(fontName: .Exo2_Medium, size: 16)
        dropDownModule.shadowColor = UIColor.appColor(.TextDarkBlue)!
        dropDownModule.backgroundColor = .white
        dropDownModule.shadowOffset = CGSize(width: 0, height: 1)
        dropDownModule.separatorColor = UIColor.lightGray
        dropDownModule.width = vc.subjectStack.frame.width
        dropDownModule.selectionBackgroundColor = UIColor.appColor(.TextDarkBlue)!
        dropDownModule.selectedTextColor = UIColor.white
        dropDownModule.selectionAction = { [weak self] (index: Int, item: String) in
            self?.vc.subjectLabel.text = item
            print(index , item)
        }
    }
}
