//
//  YHEmailInputAlertView.swift
//  galaxy
//
//  Created by davidhuangA on 2024/3/31.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHEmailInputAlertView: UIView {
    
    static let height = 217.0
    static let maxWordsCount = 30
    var editBlock: ((String?) -> Void)?
    var dismissBlock: (() -> Void)?
    
    lazy var blackMaskView: UIView = {
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        let tap = UITapGestureRecognizer(target: self, action: #selector(didWhiteContentViewTap))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_B(ofSize: 17)
        label.text = "填写要发送的邮箱"
        return label
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "my_cer_sheet_close"), for: .normal)
        btn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        return btn
    }()
    
    lazy var topLine: UIView = {
       let view = UIView()
       view.backgroundColor = .separatorColor
       return view
    }()
    
    lazy var inputContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        return view
    }()
    
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.placeholder = "请输入邮箱"
        textField.font = UIFont.PFSC_M(ofSize: 16)
        textField.tintColor = UIColor.brandMainColor
        textField.textColor = UIColor.mainTextColor
        textField.delegate = self
        textField.clearButtonMode = .whileEditing
        return textField
    }()
    
    lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.backgroundColor = .contentBkgColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickCancelBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var confirmBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("确定".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickConfirmBtn), for: .touchUpInside)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func emailInputView(defalutText: String?) -> YHEmailInputAlertView {
        let view = YHEmailInputAlertView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: Self.height))
        view.textField.text = defalutText
        return view
    }
    
    func createUI() {

        self.addSubview(whiteContentView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(closeBtn)
        whiteContentView.addSubview(topLine)
        whiteContentView.addSubview(inputContentView)
        inputContentView.addSubview(textField)
        whiteContentView.addSubview(cancelBtn)
        whiteContentView.addSubview(confirmBtn)
        
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        titleLabel.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(52.0)
        }
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24.0)
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(titleLabel)
        }
        topLine.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(titleLabel.snp.bottom)
            make.height.equalTo(1)
        }
        inputContentView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(topLine.snp.bottom).offset(20)
            make.height.equalTo(48)
        }
        textField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(20)
            make.centerY.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalTo(whiteContentView.snp.centerX).offset(-6)
            make.top.equalTo(inputContentView.snp.bottom).offset(30)
            make.height.equalTo(45)
        }
        confirmBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.left.equalTo(whiteContentView.snp.centerX).offset(6)
            make.top.equalTo(cancelBtn)
            make.height.equalTo(45)
        }
    }
}

extension YHEmailInputAlertView {
    
    @objc func dismiss() {
        self.textField.resignFirstResponder()
        UIApplication.shared.yhKeyWindow()?.endEditing(true)
        dismissBlock?()
    }
    
    @objc func didWhiteContentViewTap() {
        self.textField.becomeFirstResponder()
    }
    
    @objc func didClickCancelBtn() {
        dismiss()
    }
    
    @objc func didClickConfirmBtn() {
        if isEmptyString(textField.text) {
            YHHUD.flash(message: "邮箱不可为空")
            return
        }
        
        if let txt = textField.text, txt.isYHValidEmail {
            if let editBlock = editBlock {
                editBlock(textField.text)
            }
            dismiss()
            
        } else {
            YHHUD.flash(message: "邮箱格式有误")
            
        }
    }
}

extension YHEmailInputAlertView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.isEmpty == true { // 点击删除
            return true
        }
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newText.count > Self.maxWordsCount {
            YHHUD.flash(message: "重命名限制最多30个字符")
            return false
        }
        return true
    }
}
