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

import Foundation
import UIKit

class IdentityGateView: UIView, UITextFieldDelegate{

    // MARK: - UI Components

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

    private let titleRibbon: UIButton = {
        let button = UIButton(type: .system)
        button.setBackgroundImage(UIImage(named: "res_x8brwne3"), 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 infoLabel: 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 nameCaption: UILabel = {
        let label = UILabel()
        label.text = "姓  名"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = .white
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    private let nameField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入真实姓名"
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()

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

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

    private let confirmControl: UIButton = {
        let button = UIButton(type: .system)
        
        button.setBackgroundImage(UIImage(named: "res_ux9fin4y"), 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 dismissControl: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "res_9mx2yiyi"), for: .normal)
        button.addTarget(self, action: #selector(dismissPanel), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    // MARK: - Initialization
    init() {
        super.init(frame: .zero)
        buildUI()
        applyConstraints()
        wireKeyboardDismissal()  // Set up keyboard dismissal
    }

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

    // MARK: - UI Setup
    private func buildUI() {
        addSubview(backdropView)
        addSubview(cardImageView)
        addSubview(titleRibbon)
        addSubview(infoLabel)
        addSubview(nameCaption)
        addSubview(nameField)
        addSubview(idCaption)
        addSubview(idField)
        addSubview(confirmControl)
        addSubview(dismissControl)

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

    }

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

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

            titleRibbon.topAnchor.constraint(equalTo: cardImageView.topAnchor, constant: 10),
            titleRibbon.centerXAnchor.constraint(equalTo: cardImageView.centerXAnchor, constant: 0),
            titleRibbon.widthAnchor.constraint(equalToConstant: 132),
            titleRibbon.heightAnchor.constraint(equalToConstant: 37),
            
            infoLabel.topAnchor.constraint(equalTo: titleRibbon.bottomAnchor, constant: 14),
            infoLabel.centerXAnchor.constraint(equalTo: cardImageView.centerXAnchor, constant: 0),
            infoLabel.leadingAnchor.constraint(equalTo: cardImageView.leadingAnchor, constant: 35),
            infoLabel.trailingAnchor.constraint(equalTo: cardImageView.trailingAnchor, constant: -35),


            nameField.topAnchor.constraint(equalTo: infoLabel.bottomAnchor, constant: 17),
            nameField.trailingAnchor.constraint(equalTo: cardImageView.trailingAnchor, constant: -30),
            nameField.widthAnchor.constraint(equalToConstant: 204),
            nameField.heightAnchor.constraint(equalToConstant: 24),

            nameCaption.centerYAnchor.constraint(equalTo: nameField.centerYAnchor, constant: 0),
            nameCaption.trailingAnchor.constraint(equalTo: nameField.leadingAnchor, constant: -11),

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

            idCaption.centerYAnchor.constraint(equalTo: idField.centerYAnchor, constant: 0),
            idCaption.trailingAnchor.constraint(equalTo: idField.leadingAnchor, constant: -11),

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


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

        ])
    }

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

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

    @objc private func resignKeyboard() {
        nameField.resignFirstResponder()
        idField.resignFirstResponder()
    }

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

    // 通用 Toast
    private func flashToast(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()
                }
            }
        }
    }

}
