//
//  SpeakEleLoginViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/11.
//

import UIKit
import AuthenticationServices



class SpeakEleLoginViewCtr: SpeakEleBaseViewCtr {
    
    enum loginState {
        case login
        case register
    }
    
    private let viewModel = SpeakEleLoginViewModel()
    private let net = SpeakUserNetViewModel()
    // MARK: - ib
    @IBOutlet weak var SpeakLgTitleL: UILabel!
    
    @IBOutlet weak var SpeakLgSubTitleL: UILabel!
    
    @IBOutlet weak var SpeakEmailContentV: UIView!
    @IBOutlet weak var SpeakEamil: UITextField!
    
    @IBOutlet weak var SpeakPsContentV: UIView!
    @IBOutlet weak var SpeakPs: UITextField!
    @IBOutlet weak var SpeakSecure: UIButton!
    
    @IBOutlet weak var SpeakSetPsContentV: UIView!
    @IBOutlet weak var SpeakSetPs: UITextField!
    @IBOutlet weak var SpeakSetSecure: UIButton!
    
    @IBOutlet weak var SpeakDesc: UILabel!
    @IBOutlet var SpeakOtherLogin: [UIButton]!
    
    @IBOutlet weak var SpeakForgotPs: UIButton!
    
    @IBOutlet weak var SpeakEmailIncorrect: UIView!
    @IBOutlet weak var SpeakPsIncorrect: UIView!
    @IBOutlet weak var SpeakSetPsIncorrect: UIView!
    
    @IBOutlet weak var SpeakLoginBtn: SpeakEleButton!
    
    var state:loginState = .login
    
    private var secureTextEntry:Bool = true {
        didSet{
            SpeakPs.isSecureTextEntry = secureTextEntry
            SpeakSecure.isSelected = !secureTextEntry
        }
    }
    
    private var secureSetTextEntry:Bool = true {
        didSet{
            SpeakSetPs.isSecureTextEntry = secureSetTextEntry
            SpeakSetSecure.isSelected = !secureSetTextEntry
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        SpeakEmailIncorrect.isHidden = true
        SpeakPsIncorrect.isHidden = true
        SpeakSetPsIncorrect.isHidden = true
        secureTextEntry = true
        secureSetTextEntry = true
    }
    
    override func setup() {
        SpeakForgotPs.isHidden = !(state == .login)
        SpeakSetPsContentV.isHidden = state == .login
        SpeakSetPs.isHidden = state == .login
        SpeakSetSecure.isHidden = state == .login
        
        if state == .register {
            SpeakLgTitleL.text = "Sign up with E-mail"
            SpeakLgSubTitleL.text = "Please fill in your email address and password"
            SpeakEamil.placeholder = "E-mail address"
            SpeakPs.placeholder = "Password"
            SpeakSetPs.placeholder = "Confirm Password"
        }else{
            SpeakLgTitleL.text = "Welcome back"
            SpeakLgSubTitleL.text = "Log in to continue learning with your private AI Tutor"
            SpeakEamil.placeholder = "E-mail address"
            SpeakPs.placeholder = "Password"
        }
        
        SpeakDesc.AddTextTap(["Privacy Policy","Terms of Service."])
        let privacy = "Privacy Policy".attributed().font(UIFont.montserrat(.medium,size: 10)).underline(.single).paragraphStyle(.center,lineSpacing: 4).build()
        let terms = "Terms of Service.".attributed().font(UIFont.montserrat(.medium,size: 10)).underline(.single).paragraphStyle(.center,lineSpacing: 4).build()
        let att = "Proceeding further indicates your agreement to our ".attributed().paragraphStyle(.center,lineSpacing: 4).build().combined(with: [privacy," and ", terms])
        SpeakDesc.attributedText = att
        SpeakDesc.callblack = { [weak self] text in
            guard let v:String = text as? String else { return }
            if v == "Privacy Policy" {
                self?.PrivacyPolicy()
            }else{
                self?.TermsOfService()
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        SpeakOtherLogin.forEach { button in
            button.shadow(cornerRadius: 20, shadowColor: .init(hex: 0x000000,alpha: 0.06), offset: CGSizeMake(0, 4), opacity: 1, radius: 20)
        }
    }
    
    private func PrivacyPolicy() -> Void {
        let web = SpeakEleWebViewCtr()
        web.LoadWithUrl(url: SpeakPrivacy)
        self.navigationController?.pushViewController(web, animated: true)
    }
    
    private func TermsOfService() -> Void {
        let web = SpeakEleWebViewCtr()
        web.LoadWithUrl(url: SpeakTerms)
        self.navigationController?.pushViewController(web, animated: true)
    }

    @IBAction func SpeakForgot(_ sender: Any) {
        let forget = SpeakEleForgetViewCtr()
        self.navigationController?.pushViewController(forget, animated: true)
    }
    
    @IBAction func SpeakCreate(_ sender: Any) {
        let email = SpeakEamil.text ?? ""
        if !email.isValidEmail() {
            SpeakEmailIncorrect.isHidden = false
            SpeakEmailContentV.borderColor = .init(hex: 0xEB3B2F)
            return
        }
        SpeakEmailIncorrect.isHidden = true
        SpeakEmailContentV.borderColor = .clear
        
        let ps = SpeakPs.text ?? ""
        if ps.count <= 0 {
            SpeakPsIncorrect.isHidden = false
            SpeakPsContentV.borderColor = .init(hex: 0xEB3B2F)
            return
        }
        
        if state == .register {
            let setps = SpeakSetPs.text ?? ""
            if setps.count <= 0 || setps != ps {
                SpeakSetPsIncorrect.isHidden = false
                SpeakSetPsContentV.borderColor = .init(hex: 0xEB3B2F)
                return
            }else{
                SpeakSetPsIncorrect.isHidden = true
                SpeakSetPsContentV.borderColor = .clear
            }
        }
        SpeakPsIncorrect.isHidden = true
        SpeakPsContentV.borderColor = .clear
        if state == .register { 
            net.logion(param: ["email":email,
                               "password":ps,
                               "type":3,
                               "isLogin":false]) {[weak self] (success, user: UserMode?)  in
                if success {
                    SpeakElePublicManager.share.PublicData.userInfo.assign(from: user)
                    self?.toGuide()
                }
            }
        }else{
            net.logion(param: ["email":email,
                               "password":ps,
                               "type":3,
                               "isLogin":true]) {[weak self] (success, user: UserMode?)  in
                if success {
                    SpeakElePublicManager.share.PublicData.userInfo.assign(from: user)
                    self?.toGuide()
                }
            }
        }
    }
    
    @IBAction func SpeakSecureButton(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender == SpeakSecure{
            secureTextEntry = !sender.isSelected
        }else{
            secureSetTextEntry = !sender.isSelected
        }
    }
    
    @IBAction func SpeakThreeLoginTaps(_ sender: UIButton) {
        if sender == SpeakOtherLogin.last {
            viewModel.AppleLogin { response in
                switch response {
                case .success(let token):
                    self.net.logion(param: ["appleUserId":token,
                                            "type":1,
                                            "isLogin":true]) { [weak self] (succsee, data:UserMode?) in
                        if succsee {
                            SpeakElePublicManager.share.PublicData.userInfo.assign(from: data)
                            self?.toGuide()
                        }
                    }
                    break
                case .failure(let error):
                    self.Alert(message: error.localizedDescription)
                    break
                }
            }
        }else{
            viewModel.googleLogin { response in
                switch response {
                case .success(let token):
                    self.net.logion(param: ["googleUserId":token,
                                            "type":2,
                                            "isLogin":true]) { [weak self] (succsee, data:UserMode?) in
                        if succsee {
                            SpeakElePublicManager.share.PublicData.userInfo.assign(from: data)
                            self?.toGuide()
                        }
                    }
                    break
                case .failure(let error):
                    self.Alert(message: error.localizedDescription)
                    break
                }
            }
        }
    }
    
    private func toGuide() -> Void {
        if state == .register || SpeakElePublicManager.share.PublicData.state == .login{
            let nav = SpeakEleBaseNavigationCtr(rootViewController: SpeakEleTabbarViewCtr())
            SpWindow.switchToController(nav)
        }else{
            let guide = SpeakEleGuideViewCtr()
            self.navigationController?.pushViewController(guide, animated: true)
        }
    }
}
