//
//  LoginTextField.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 登录页账号输入框，对应 Android `PhoneInputField`。
final class LoginTextField: UIView {

    private let textField = UITextField()

    var text: String {
        get { textField.text ?? "" }
        set { textField.text = newValue }
    }

    var onTextChange: ((String) -> Void)?
    var onReturnKey: (() -> Void)?
    var onEditingDidEnd: (() -> Void)?

    init(placeholder: String) {
        super.init(frame: .zero)
        setupUI(placeholder: placeholder)
        setupConstraints()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @discardableResult
    override func becomeFirstResponder() -> Bool {
        textField.becomeFirstResponder()
    }

    private func setupUI(placeholder: String) {
        backgroundColor = AppColor.inputBackground
        layer.cornerRadius = 12
        clipsToBounds = true

        textField.font = .systemFont(ofSize: 14)
        textField.textColor = AppColor.text333
        textField.autocapitalizationType = .none
        textField.autocorrectionType = .no
        textField.returnKeyType = .next
        textField.clearButtonMode = .whileEditing
        textField.delegate = self

        let attributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: AppColor.placeholder,
            .font: UIFont.systemFont(ofSize: 14),
        ]
        textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)

        textField.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
        textField.addTarget(self, action: #selector(editingDidEnd), for: .editingDidEnd)
        addSubview(textField)
    }

    private func setupConstraints() {
        snp.makeConstraints { make in
            make.height.equalTo(46)
        }

        textField.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.centerY.equalToSuperview()
        }
    }

    @objc private func textDidChange() {
        onTextChange?(text)
    }

    @objc private func editingDidEnd() {
        onEditingDidEnd?()
    }
}

extension LoginTextField: UITextFieldDelegate {

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        onReturnKey?()
        return true
    }
}
