//
//  DialViewController.swift
//  JJPhoneDemo
//
//

import UIKit

class DialViewController: UIViewController {

    private let phoneService: PhoneServiceProtocol = PhoneService.shared

    private let dialKeyboard = DialKeyboardView()

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    private let statusLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        if #available(iOS 13.0, *) {
            label.textColor = .secondaryLabel
        } else {
            label.textColor = .gray
        }
        label.font = .systemFont(ofSize: 14)
        label.numberOfLines = 0
        label.text = ""  // 初始为空，只显示 SIP 连接状态
        return label
    }()
    
    private let phoneNumberLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.textColor = .black
        if #available(iOS 13.0, *) {
            label.font = .systemFont(ofSize: 36, weight: .medium)  // 调大字体
        } else {
            label.font = .systemFont(ofSize: 36, weight: .semibold)  // 调大字体
        }
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.5
        label.text = ""
        return label
    }()
    
    private let 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 let promptLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        if #available(iOS 13.0, *) {
            label.textColor = .secondaryLabel
        } else {
            label.textColor = .gray
        }
        label.font = .systemFont(ofSize: 16)
        label.text = "请输入电话号码"
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "拨号"
        if #available(iOS 13.0, *) {
            view.backgroundColor = .systemBackground
        } else {
            view.backgroundColor = .white
        }
        
        // 添加右上角设置按钮
        let settingsButton: UIBarButtonItem
        if #available(iOS 13.0, *) {
            settingsButton = UIBarButtonItem(
                image: UIImage(systemName: "gearshape.fill"),
                style: .plain,
                target: self,
                action: #selector(settingsButtonTapped)
            )
        } else {
            settingsButton = UIBarButtonItem(
                title: "设置",
                style: .plain,
                target: self,
                action: #selector(settingsButtonTapped)
            )
        }
        navigationItem.rightBarButtonItem = settingsButton
        
        setupUI()
        setupCallbacks()
    }
    
    @objc private func settingsButtonTapped() {
        let settingsVC = CallSettingsViewController()
        navigationController?.pushViewController(settingsVC, animated: true)
    }
    
    private func setupUI() {
        view.backgroundColor = UIConstants.Color.dialBackground
        
        view.addSubview(phoneNumberLabel)
        view.addSubview(deleteButton)
        view.addSubview(promptLabel)
        view.addSubview(dialKeyboard)
        view.addSubview(statusLabel)
        
        phoneNumberLabel.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        promptLabel.translatesAutoresizingMaskIntoConstraints = false
        dialKeyboard.translatesAutoresizingMaskIntoConstraints = false
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        
        dialKeyboard.delegate = self
        dialKeyboard.setCallButtonTarget(self, action: #selector(callAction))
        
        // 隐藏键盘内部的号码显示和删除按钮
        dialKeyboard.hideNumberLabel()
        dialKeyboard.hideDeleteButton()
        
        // 删除按钮事件
        deleteButton.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(deleteAllAction(_:)))
        deleteButton.addGestureRecognizer(longPress)
        
        // 创建键盘高度约束并降低优先级
        let keyboardHeightConstraint = dialKeyboard.heightAnchor.constraint(equalTo: dialKeyboard.widthAnchor, multiplier: 482.0/375.0)
        keyboardHeightConstraint.priority = UILayoutPriority(999)
        
        NSLayoutConstraint.activate([
            // 号码标签：顶部距离安全区域至少20pt，高度至少40pt
            phoneNumberLabel.topAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor, constant: UIConstants.Layout.verticalPadding),
            phoneNumberLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 60),
            phoneNumberLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -60),
            phoneNumberLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 40),
            phoneNumberLabel.bottomAnchor.constraint(equalTo: promptLabel.topAnchor, constant: -12),
            
            // 删除按钮在号码标签右侧，同一行
            deleteButton.widthAnchor.constraint(equalToConstant: 40),
            deleteButton.heightAnchor.constraint(equalToConstant: 40),
            deleteButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -UIConstants.Layout.horizontalPadding),
            deleteButton.centerYAnchor.constraint(equalTo: phoneNumberLabel.centerYAnchor),
            
            // 提示标签在拨号盘上方
            promptLabel.bottomAnchor.constraint(equalTo: dialKeyboard.topAnchor, constant: -UIConstants.Layout.verticalPadding),
            promptLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            promptLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: UIConstants.Layout.horizontalPadding),
            promptLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -UIConstants.Layout.horizontalPadding),
            
            // 键盘：居中显示，宽度等于视图宽度，高度按比例计算（优先级降低）
            dialKeyboard.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            dialKeyboard.widthAnchor.constraint(equalTo: view.widthAnchor),
            keyboardHeightConstraint,
            // 确保底部有足够空间显示状态标签（优先级更高）
            dialKeyboard.bottomAnchor.constraint(lessThanOrEqualTo: statusLabel.topAnchor, constant: UIConstants.Layout.verticalPadding),
            
            // 状态标签固定在底部
            statusLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -UIConstants.Layout.verticalPadding),
            statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: UIConstants.Layout.horizontalPadding),
            statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -UIConstants.Layout.horizontalPadding)
        ])
    }
    
    @objc private func deleteAction() {
        dialKeyboard.deleteLastCharacter()
        updatePhoneNumberDisplay()
    }
    
    @objc private func deleteAllAction(_ gesture: UILongPressGestureRecognizer) {
        if gesture.state == .began {
            dialKeyboard.clearNumber()
            updatePhoneNumberDisplay()
        }
    }
    
    private func updatePhoneNumberDisplay() {
        phoneNumberLabel.text = dialKeyboard.getPhoneNumber()
        deleteButton.isHidden = dialKeyboard.getPhoneNumber().isEmpty
    }
    
    private func setupCallbacks() {
        // 监听连接状态
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipConnected.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.statusLabel.text = "电话服务已连接，可以拨打电话"
        }
        
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipConnectFailed.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] notification in
            if let userInfo = notification.userInfo,
               let reason = userInfo[kSIPReasonDescriptionKey] as? String {
                self?.statusLabel.text = "电话服务连接失败：\(reason)"
            } else {
                self?.statusLabel.text = "电话服务连接失败"
            }
        }
        
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipDisconnected.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.statusLabel.text = "电话服务已断开连接"
        }
    }
    
    @objc private func callAction() {
        let phoneNumber = dialKeyboard.getPhoneNumber()

        guard !phoneNumber.isEmpty else {
            statusLabel.text = "请先输入要拨打的号码"
            return
        }

        guard phoneService.canMakeCall() else {
            statusLabel.text = "当前无法拨打，请确认已登录且没有正在进行的通话"
            return
        }

        phoneService.makeCall(number: phoneNumber, userData: ["test": "test"])

        let call = Call()
        call.phoneNumber = phoneNumber
        call.callType = .outgoing
        call.status = .calling

        let callVC = ActiveCallViewController()
        callVC.call = call
        navigationController?.pushViewController(callVC, animated: true)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension DialViewController: DialKeyboardViewDelegate {
    func dialKeyboardDidInputNumber(_ number: String) {
        // 更新显示的号码
        updatePhoneNumberDisplay()
    }
    
    func dialKeyboardDidDelete() {
        // 更新显示的号码
        updatePhoneNumberDisplay()
    }
    
    func dialKeyboardDidDeleteAll() {
        // 更新显示的号码
        updatePhoneNumberDisplay()
    }
}

