//
//  DialKeyboardView.swift
//  JJPhoneDemo
//
//

import UIKit

protocol DialKeyboardViewDelegate: AnyObject {
    func dialKeyboardDidInputNumber(_ number: String)
    func dialKeyboardDidDelete()
    func dialKeyboardDidDeleteAll()
}

class DialKeyboardView: UIView {
    
    weak var delegate: DialKeyboardViewDelegate?
    
    var numberLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        if #available(iOS 13.0, *) {
            label.font = .systemFont(ofSize: 28, weight: .medium)
        } else {
            label.font = .systemFont(ofSize: 28, weight: .semibold)
        }
        label.textColor = .black
        label.adjustsFontSizeToFitWidth = true
        label.text = ""
        return label
    }()
    
    private var deleteButton: UIButton = {
        let btn = UIButton(type: .system)
        if #available(iOS 13.0, *) {
            btn.setImage(UIImage(systemName: "delete.left"), for: .normal)
        } else {
            btn.setTitle("删除", for: .normal)
        }
        btn.tintColor = .black
        btn.isHidden = true  // 初始隐藏，有内容后显示
        return btn
    }()
    
    private var callButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .systemGreen
        btn.layer.cornerRadius = 35
        if #available(iOS 13.0, *) {
            btn.setImage(UIImage(systemName: "phone.fill"), for: .normal)
        } else {
            btn.setTitle("📞", for: .normal)
            btn.titleLabel?.font = .systemFont(ofSize: 24)
        }
        btn.tintColor = .white
        return btn
    }()
    
    private var numberButtons: [UIButton] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIConstants.Color.dialBackground
        
        addSubview(numberLabel)
        // 删除按钮默认不添加，由外部控制
        addSubview(callButton)
        
        numberLabel.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        callButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 默认隐藏删除按钮
        deleteButton.isHidden = true
        
        // 创建数字键盘按钮
        let numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#"]
        
        for (index, number) in numbers.enumerated() {
            let btn = createNumberButton(number: number, tag: index)
            numberButtons.append(btn)
            addSubview(btn)
        }
        
        setupConstraints()
        setupActions()
    }
    
    private func createNumberButton(number: String, tag: Int) -> UIButton {
        let btn = UIButton(type: .custom)
        btn.tag = tag
        btn.backgroundColor = UIConstants.Color.dialButtonBackground
        btn.layer.cornerRadius = 35
        btn.setTitle(number, for: .normal)
        btn.setTitleColor(.black, for: .normal)
        if #available(iOS 13.0, *) {
            btn.titleLabel?.font = .systemFont(ofSize: 28, weight: .medium)
        } else {
            btn.titleLabel?.font = .systemFont(ofSize: 28, weight: .semibold)
        }
        btn.translatesAutoresizingMaskIntoConstraints = false
        return btn
    }
    
    private func setupConstraints() {
        // 参考原项目的布局参数
        let buttonSize: CGFloat = 75
        let screenWidth = UIScreen.main.bounds.width
        let spacing: CGFloat = (screenWidth - buttonSize * 3 - 40) / 4.0  // 参考原项目计算方式
        let topSpacing: CGFloat = 5
        let labelHeight: CGFloat = 40
        let labelTopMargin: CGFloat = 45  // 号码标签到按钮的间距
        let verticalSpacing: CGFloat = 15  // 按钮之间的垂直间距（更紧凑）
        
        NSLayoutConstraint.activate([
            // 号码标签居中（删除按钮已移到外部，这里不需要留空间）
            // 由于外部有号码显示，这里隐藏，但保留约束避免布局问题
            numberLabel.topAnchor.constraint(equalTo: topAnchor, constant: 0),
            numberLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 40),
            numberLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -40),
            numberLabel.heightAnchor.constraint(equalToConstant: 0)  // 高度设为0，不占用空间
        ])
        
        // 删除按钮约束（但不添加到视图，由外部控制）
        // 删除按钮默认不显示，如果需要显示，调用 showDeleteButton()
        
        // 数字按钮布局 (3列4行: 1-9, *, 0, #)
        // 按钮顺序: 1,2,3,4,5,6,7,8,9,*,0,#
        for (index, button) in numberButtons.enumerated() {
            let row = index / 3
            let col = index % 3
            
            NSLayoutConstraint.activate([
                button.widthAnchor.constraint(equalToConstant: buttonSize),
                button.heightAnchor.constraint(equalToConstant: buttonSize),
                button.leadingAnchor.constraint(equalTo: leadingAnchor, constant: spacing + 20 + CGFloat(col) * (buttonSize + spacing)),
                // 由于 numberLabel 高度为0，直接从顶部开始布局
                button.topAnchor.constraint(equalTo: topAnchor, constant: 10 + CGFloat(row) * (buttonSize + verticalSpacing))
            ])
        }
        
        // 拨打按钮：在 0 按钮的下方
        if numberButtons.count >= 12 {
            let zeroButton = numberButtons[10]  // 0 按钮 (index 10, 第4行第2列)
            
            NSLayoutConstraint.activate([
                // 拨打按钮：在 0 按钮的下方，居中
                callButton.widthAnchor.constraint(equalToConstant: buttonSize),
                callButton.heightAnchor.constraint(equalToConstant: buttonSize),
                callButton.centerXAnchor.constraint(equalTo: zeroButton.centerXAnchor),
                callButton.topAnchor.constraint(equalTo: zeroButton.bottomAnchor, constant: verticalSpacing)
            ])
        }
    }
    
    private func setupActions() {
        // 删除按钮事件在 showDeleteButton() 时添加
        // deleteButton.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
        // let longPress = UILongPressGestureRecognizer(target: self, action: #selector(deleteAllAction(_:)))
        // deleteButton.addGestureRecognizer(longPress)
        
        for button in numberButtons {
            button.addTarget(self, action: #selector(numberButtonTapped(_:)), for: .touchUpInside)
        }
    }
    
    @objc private func numberButtonTapped(_ sender: UIButton) {
        guard let number = sender.currentTitle else { return }
        let currentText = numberLabel.text ?? ""
        if currentText.count < 16 {
            numberLabel.text = currentText + number
            updateDeleteButtonVisibility()
            delegate?.dialKeyboardDidInputNumber(number)
        }
    }
    
    @objc private func deleteAction() {
        let currentText = numberLabel.text ?? ""
        if !currentText.isEmpty {
            numberLabel.text = String(currentText.dropLast())
            updateDeleteButtonVisibility()
            delegate?.dialKeyboardDidDelete()
        }
    }
    
    @objc private func deleteAllAction(_ gesture: UILongPressGestureRecognizer) {
        if gesture.state == .began {
            numberLabel.text = ""
            updateDeleteButtonVisibility()
            delegate?.dialKeyboardDidDeleteAll()
        }
    }
    
    /// 更新删除按钮的显示状态
    private func updateDeleteButtonVisibility() {
        let hasText = !(numberLabel.text?.isEmpty ?? true)
        deleteButton.isHidden = !hasText
    }
    
    func setCallButtonTarget(_ target: Any?, action: Selector) {
        callButton.addTarget(target, action: action, for: .touchUpInside)
    }
    
    func getPhoneNumber() -> String {
        return numberLabel.text ?? ""
    }
    
    func clearNumber() {
        numberLabel.text = ""
        updateDeleteButtonVisibility()
    }
    
    /// 隐藏键盘内部的号码显示（当外部有号码显示时使用）
    func hideNumberLabel() {
        numberLabel.isHidden = true
    }
    
    /// 显示键盘内部的号码显示
    func showNumberLabel() {
        numberLabel.isHidden = false
    }
    
    /// 隐藏键盘内部的删除按钮（当外部有删除按钮时使用）
    func hideDeleteButton() {
        if deleteButton.superview != nil {
            deleteButton.removeFromSuperview()  // 完全移除，避免显示
        }
    }
    
    /// 显示键盘内部的删除按钮
    func showDeleteButton() {
        if deleteButton.superview == nil {
            addSubview(deleteButton)
            deleteButton.translatesAutoresizingMaskIntoConstraints = false
            // 重新添加约束
            NSLayoutConstraint.activate([
                deleteButton.widthAnchor.constraint(equalToConstant: 40),
                deleteButton.heightAnchor.constraint(equalToConstant: 40),
                deleteButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),
                deleteButton.centerYAnchor.constraint(equalTo: numberLabel.centerYAnchor)
            ])
            // 添加事件
            deleteButton.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
            let longPress = UILongPressGestureRecognizer(target: self, action: #selector(deleteAllAction(_:)))
            deleteButton.addGestureRecognizer(longPress)
        }
        deleteButton.isHidden = false
        updateDeleteButtonVisibility()
    }
    
    /// 删除最后一个字符（供外部调用）
    func deleteLastCharacter() {
        let currentText = numberLabel.text ?? ""
        if !currentText.isEmpty {
            numberLabel.text = String(currentText.dropLast())
            updateDeleteButtonVisibility()
        }
    }
}


