//
//  RealNamePopupView.swift
//  RoderickRalph
//
//  Created by Neoa on 2025/8/20.
//

import Foundation
import UIKit

class RealNamePopupView: UIView, UITextFieldDelegate{

    // MARK: - UI Components

    private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)  // Semi-transparent gray background
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let popupBackgroundImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "pqan335")  // Background image for the pop-up
        imageView.contentMode = .scaleToFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    private let titleButton: UIButton = {
        let button = UIButton(type: .system)
        button.setBackgroundImage(UIImage(named: "pqan333"), for: .normal)
        button.setTitle("实名认证", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    private let detailLabel: UILabel = {
        let label = UILabel()
        label.text = "根据国家相关法规规定，请使用有效身份证进行实名认证。（该信息仅用于实名登记，不会向任何第三方泄露）"
        label.font = UIFont.systemFont(ofSize: 11)
        label.textColor = .white
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private let nameLabel: UILabel = {
        let label = UILabel()
        label.text = "姓  名"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = .white
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    private let nameTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入真实姓名"
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()

    
    private let idLabel: UILabel = {
        let label = UILabel()
        label.text = "身份证号"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = .white
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    private let idNumberTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入有效的身份证号"
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()

    private let confirmButton: UIButton = {
        let button = UIButton(type: .system)
        
        button.setBackgroundImage(UIImage(named: "tqan323"), for: .normal)
        button.setTitle("认证", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        button.contentHorizontalAlignment = .center
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    
    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "pqan334"), for: .normal)
        button.addTarget(self, action: #selector(closePopup), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    // MARK: - Initialization
    init() {
        super.init(frame: .zero)
        setupUI()
        setupConstraints()
        setupKeyboardDismissal()  // Set up keyboard dismissal
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - UI Setup
    private func setupUI() {
        addSubview(backgroundView)
        addSubview(popupBackgroundImageView)
        addSubview(titleButton)
        addSubview(detailLabel)
        addSubview(nameLabel)
        addSubview(nameTextField)
        addSubview(idLabel)
        addSubview(idNumberTextField)
        addSubview(confirmButton)
        addSubview(closeButton)

        // If you want the dimmed background to also close the popup, uncomment below:
        // let tapGesture = UITapGestureRecognizer(target: self, action: #selector(closePopup))
        // backgroundView.addGestureRecognizer(tapGesture)
        
        nameTextField.delegate = self
        idNumberTextField.delegate = self
        confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)

    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
            // Background view
            backgroundView.topAnchor.constraint(equalTo: topAnchor),
            backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor),
            backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor),
            backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor),

            popupBackgroundImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            popupBackgroundImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
            popupBackgroundImageView.widthAnchor.constraint(equalToConstant: 333),
            popupBackgroundImageView.heightAnchor.constraint(equalToConstant: 266),

            titleButton.topAnchor.constraint(equalTo: popupBackgroundImageView.topAnchor, constant: 10),
            titleButton.centerXAnchor.constraint(equalTo: popupBackgroundImageView.centerXAnchor, constant: 0),
            titleButton.widthAnchor.constraint(equalToConstant: 132),
            titleButton.heightAnchor.constraint(equalToConstant: 37),
            
            detailLabel.topAnchor.constraint(equalTo: titleButton.bottomAnchor, constant: 14),
            detailLabel.centerXAnchor.constraint(equalTo: popupBackgroundImageView.centerXAnchor, constant: 0),
            detailLabel.leadingAnchor.constraint(equalTo: popupBackgroundImageView.leadingAnchor, constant: 35),
            detailLabel.trailingAnchor.constraint(equalTo: popupBackgroundImageView.trailingAnchor, constant: -35),


            nameTextField.topAnchor.constraint(equalTo: detailLabel.bottomAnchor, constant: 17),
            nameTextField.trailingAnchor.constraint(equalTo: popupBackgroundImageView.trailingAnchor, constant: -30),
            nameTextField.widthAnchor.constraint(equalToConstant: 204),
            nameTextField.heightAnchor.constraint(equalToConstant: 24),

            nameLabel.centerYAnchor.constraint(equalTo: nameTextField.centerYAnchor, constant: 0),
            nameLabel.trailingAnchor.constraint(equalTo: nameTextField.leadingAnchor, constant: -11),

            idNumberTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor, constant: 8),
            idNumberTextField.trailingAnchor.constraint(equalTo: nameTextField.trailingAnchor, constant: 0),
            idNumberTextField.widthAnchor.constraint(equalToConstant: 204),
            idNumberTextField.heightAnchor.constraint(equalToConstant: 24),

            idLabel.centerYAnchor.constraint(equalTo: idNumberTextField.centerYAnchor, constant: 0),
            idLabel.trailingAnchor.constraint(equalTo: idNumberTextField.leadingAnchor, constant: -11),

            
            confirmButton.topAnchor.constraint(equalTo: idNumberTextField.bottomAnchor, constant: 20),
            confirmButton.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0),
            confirmButton.widthAnchor.constraint(equalToConstant: 211),
            confirmButton.heightAnchor.constraint(equalToConstant: 42),


            closeButton.topAnchor.constraint(equalTo: popupBackgroundImageView.topAnchor, constant: -12),
            closeButton.trailingAnchor.constraint(equalTo: popupBackgroundImageView.trailingAnchor, constant: 12),
            closeButton.widthAnchor.constraint(equalToConstant: 24),
            closeButton.heightAnchor.constraint(equalToConstant: 24),

        ])
    }

    // MARK: - Actions
    @objc private func closePopup() {
        removeFromSuperview()
    }
    
    @objc private func confirmButtonTapped() {
        // Perform validation checks
        if nameTextField.text?.isEmpty ?? true {
            showToast(message: "姓名不能为空")
        } else if idNumberTextField.text?.isEmpty ?? true {
            showToast(message: "身份证号不能为空")
        } else {
            // Show success message
            showToast(message: "认证成功")
        }
    }

    
    // MARK: - Keyboard Dismissal
    private func setupKeyboardDismissal() {
        // Tap gesture to dismiss keyboard when tapping outside the text fields
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        self.addGestureRecognizer(tapGesture)
    }

    @objc private func dismissKeyboard() {
        nameTextField.resignFirstResponder()
        idNumberTextField.resignFirstResponder()
    }

    // MARK: - UITextFieldDelegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // Dismiss the keyboard when the return key is pressed
        textField.resignFirstResponder()
        return true
    }

    // 通用 Toast
    private func showToast(message: String) {
        let toastLabel = UILabel()
        toastLabel.text = message
        toastLabel.font = UIFont.systemFont(ofSize: 14)
        toastLabel.textColor = .white
        toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        toastLabel.textAlignment = .center
        toastLabel.alpha = 0.0
        toastLabel.layer.cornerRadius = 8
        toastLabel.clipsToBounds = true
        toastLabel.translatesAutoresizingMaskIntoConstraints = false

        addSubview(toastLabel)
        NSLayoutConstraint.activate([
            toastLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
            toastLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            toastLabel.widthAnchor.constraint(equalToConstant: 160),
            toastLabel.heightAnchor.constraint(equalToConstant: 40)
        ])

        UIView.animate(withDuration: 0.3) {
            toastLabel.alpha = 1.0
        } completion: { _ in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                UIView.animate(withDuration: 0.3) {
                    toastLabel.alpha = 0.0
                } completion: { _ in
                    toastLabel.removeFromSuperview()
                }
            }
        }
    }

}
