//
//  PhoneMainViewController.swift
//  JJPhoneDemo
//
//

import UIKit

class PhoneMainViewController: UIViewController, UITextFieldDelegate {
    
    private let accountTextField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "账号"
        tf.borderStyle = .roundedRect
        tf.autocapitalizationType = .none
        tf.autocorrectionType = .no
        tf.keyboardType = .default
        tf.returnKeyType = .done
        return tf
    }()
    
    private let passwordTextField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "密码"
        tf.borderStyle = .roundedRect
        tf.isSecureTextEntry = true
        tf.autocapitalizationType = .none
        tf.autocorrectionType = .no
        tf.returnKeyType = .done
        return tf
    }()
    
    private let passwordPkTextField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "秘钥（可选，如果填写则使用秘钥登录）"
        tf.borderStyle = .roundedRect
        tf.autocapitalizationType = .none
        tf.autocorrectionType = .no
        tf.returnKeyType = .done
        return tf
    }()
    
    private let loginButton: UIButton = {
        let btn = UIButton(type: .system)
        btn.setTitle("登录", for: .normal)
        btn.backgroundColor = .systemGreen
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = 8
        return btn
    }()
    
    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 = 10
        label.text = "未登录电话服务"
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = L.Main.titleCalls
        if #available(iOS 13.0, *) {
            view.backgroundColor = .systemBackground
        } else {
            view.backgroundColor = .white
        }
        
        // 添加左上角环境切换按钮
        updateEnvironmentButton()
        
        // 添加右上角导出日志按钮
        setupExportLogButton()
        
        setupUI()
        setupCallbacks()
    }
    
    private func updateEnvironmentButton() {
        let environment = PhoneConfig.shared.environment
        let title = environment == .production ? "生产" : "测试"
        let button = UIBarButtonItem(
            title: title,
            style: .plain,
            target: self,
            action: #selector(environmentButtonTapped)
        )
        navigationItem.leftBarButtonItem = button
    }
    
    private func setupExportLogButton() {
        let businessLogButton = UIBarButtonItem(
            title: "业务日志",
            style: .plain,
            target: self,
            action: #selector(exportBusinessLogButtonTapped)
        )
        let sipLogButton = UIBarButtonItem(
            title: "SIP日志",
            style: .plain,
            target: self,
            action: #selector(exportSIPLogButtonTapped)
        )
        navigationItem.rightBarButtonItems = [sipLogButton, businessLogButton]
    }
    
    @objc private func exportBusinessLogButtonTapped(_ sender: UIBarButtonItem) {
        exportLog(fileName: "voip.log", logTitle: "业务日志", barButtonItem: sender)
    }
    
    @objc private func exportSIPLogButtonTapped(_ sender: UIBarButtonItem) {
        exportLog(fileName: "voip_pjsip.log", logTitle: "SIP日志", barButtonItem: sender)
    }
    
    private func exportLog(fileName: String, logTitle: String, barButtonItem: UIBarButtonItem) {
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let logDirectory = documentsPath.appendingPathComponent("VoIPLogs")
        let logPath = logDirectory.appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: logPath.path) else {
            let alert = UIAlertController(
                title: "\(logTitle)导出",
                message: "当前没有可导出的\(logTitle)文件。",
                preferredStyle: .alert
            )
            alert.addAction(UIAlertAction(title: L.General.ok, style: .default))
            present(alert, animated: true)
            return
        }
        
        let activityVC = UIActivityViewController(
            activityItems: [logPath],
            applicationActivities: nil
        )
        
        if let popover = activityVC.popoverPresentationController {
            popover.barButtonItem = barButtonItem
        }
        
        present(activityVC, animated: true)
    }
    
    @objc private func environmentButtonTapped() {
        let alert = UIAlertController(
            title: "选择环境",
            message: nil,
            preferredStyle: .actionSheet
        )
        
        let currentEnvironment = PhoneConfig.shared.environment
        
        // 生产环境选项
        alert.addAction(UIAlertAction(
            title: "生产环境" + (currentEnvironment == .production ? " ✓" : ""),
            style: .default
        ) { [weak self] _ in
            PhoneConfig.shared.environment = .production
            self?.updateEnvironmentButton()
        })
        
        // 测试环境选项
        alert.addAction(UIAlertAction(
            title: "测试环境" + (currentEnvironment == .development ? " ✓" : ""),
            style: .default
        ) { [weak self] _ in
            PhoneConfig.shared.environment = .development
            self?.updateEnvironmentButton()
        })
        
        alert.addAction(UIAlertAction(title: L.General.cancel, style: .cancel))
        
        // iPad 支持
        if let popover = alert.popoverPresentationController {
            popover.barButtonItem = navigationItem.rightBarButtonItem
        }
        
        present(alert, animated: true)
    }
    
    private func setupUI() {
        view.addSubview(accountTextField)
        view.addSubview(passwordTextField)
        view.addSubview(passwordPkTextField)
        view.addSubview(loginButton)
        view.addSubview(statusLabel)
        
        accountTextField.translatesAutoresizingMaskIntoConstraints = false
        passwordTextField.translatesAutoresizingMaskIntoConstraints = false
        passwordPkTextField.translatesAutoresizingMaskIntoConstraints = false
        loginButton.translatesAutoresizingMaskIntoConstraints = false
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            // 账号输入框
            accountTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            accountTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            accountTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -100),
            accountTextField.heightAnchor.constraint(equalToConstant: 44),
            
            // 密码输入框
            passwordTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            passwordTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            passwordTextField.topAnchor.constraint(equalTo: accountTextField.bottomAnchor, constant: 16),
            passwordTextField.heightAnchor.constraint(equalToConstant: 44),
            
            // 秘钥输入框
            passwordPkTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            passwordPkTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            passwordPkTextField.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor, constant: 16),
            passwordPkTextField.heightAnchor.constraint(equalToConstant: 44),
            
            // 登录按钮
            loginButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            loginButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            loginButton.topAnchor.constraint(equalTo: passwordPkTextField.bottomAnchor, constant: 24),
            loginButton.heightAnchor.constraint(equalToConstant: 44),
            
            // 状态标签在底部
            statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            statusLabel.topAnchor.constraint(greaterThanOrEqualTo: loginButton.bottomAnchor, constant: 20),
            statusLabel.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20)
        ])
        
        loginButton.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        
        // 加载保存的账号密码
        let config = PhoneConfig.shared
        accountTextField.text = config.account
        passwordTextField.text = config.password
        
        // 添加输入框监听，实时更新 PhoneConfig
        accountTextField.addTarget(self, action: #selector(accountTextFieldDidChange), for: .editingChanged)
        passwordTextField.addTarget(self, action: #selector(passwordTextFieldDidChange), for: .editingChanged)
        
        // 键盘 return 键为 Done，点击收起键盘
        accountTextField.delegate = self
        passwordTextField.delegate = self
        passwordPkTextField.delegate = self
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    @objc private func accountTextFieldDidChange() {
        if let account = accountTextField.text {
            PhoneConfig.shared.account = account
        }
    }
    
    @objc private func passwordTextFieldDidChange() {
        if let password = passwordTextField.text {
            PhoneConfig.shared.password = password
        }
    }
    
    private func setupCallbacks() {
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipConnected.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] _ in
            guard let self = self else { return }
            
            // 更新状态标签
            self.statusLabel.text = "SIP 已连接"
            
            // 更新登录按钮
            self.loginButton.setTitle("已登录", for: .normal)
            self.loginButton.backgroundColor = .systemGray
            self.loginButton.isEnabled = true
            
            // 登录成功后，仅当当前在主页时自动跳转到拨号页面（避免在 DialViewController 内重新注册 SIP 时再次 push）
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                guard self.navigationController?.topViewController === self else { return }
                let dialVC = DialViewController()
                self.navigationController?.pushViewController(dialVC, animated: true)
            }
        }
        
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipDisconnected.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.statusLabel.text = "电话服务已断开"
            self?.loginButton.setTitle("登录", for: .normal)
            self?.loginButton.backgroundColor = .systemGreen
            self?.loginButton.isEnabled = true
        }
        
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipConnectFailed.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] notification in
            self?.statusLabel.text = "电话服务连接失败"
            self?.loginButton.setTitle("登录", for: .normal)
            self?.loginButton.backgroundColor = .systemGreen
            self?.loginButton.isEnabled = true
            
            if let userInfo = notification.userInfo,
               let reason = userInfo[kSIPReasonDescriptionKey] as? String {
                self?.statusLabel.text = "电话服务连接失败：\(reason)"
            }
        }
        
        // 监听被踢下线通知
        NotificationCenter.default.addObserver(
            forName: NSNotification.Name(NSNotification.Name.sipKickedOut.rawValue),
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.handleKickedOut()
        }
    }
    
    /// 处理被踢下线
    private func handleKickedOut() {
        // 弹出提示框
        let alert = UIAlertController(
            title: "账号已在其他设备登录",
            message: "当前设备已被登出，如需继续使用，请重新登录。",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: L.General.ok, style: .default) { [weak self] _ in
            self?.clearLoginState()
        })
        
        present(alert, animated: true)
    }
    
    /// 清理登录状态
    private func clearLoginState() {
        // 登出 SIP
        PhoneService.shared.logout()
        
        // 更新 UI 状态
        statusLabel.text = "已退出登录"
        loginButton.setTitle("登录", for: .normal)
        loginButton.backgroundColor = .systemGreen
        loginButton.isEnabled = true
        
        // 如果当前在拨号页面或其他页面，返回登录页面
        if let navigationController = navigationController {
            navigationController.popToViewController(self, animated: true)
        }
    }
    
    @objc private func loginAction() {
        // 收起键盘
        view.endEditing(true)
        
        guard let account = accountTextField.text, !account.isEmpty else {
            statusLabel.text = "请填写账号"
            return
        }
        
        // 保存账号到配置
        let config = PhoneConfig.shared
        config.account = account
        
        let password = passwordTextField.text
        let passwordPk = passwordPkTextField.text?.isEmpty == false ? passwordPkTextField.text : nil
        
        // 如果填写了密码，保存密码
        if let password = password, !password.isEmpty {
            config.password = password
        }
        
        // 开始登录流程
        startLoginFlow(account: account, password: password, passwordPk: passwordPk)
    }
    
    /// 开始完整的登录流程：登录 -> 连接Socket -> 获取SIP信息 -> 登录SIP
    private func startLoginFlow(account: String, password: String?, passwordPk: String?) {
        // 获取环境配置（生产环境或开发环境）
        let environment = PhoneConfig.shared.environment
        
        self.statusLabel.text = "正在初始化电话服务..."
        self.loginButton.isEnabled = false
        
        // 初始化 VoIP 服务
        let initResult = PhoneService.shared.initialize()
        if initResult != 0 {
            self.statusLabel.text = "初始化失败，请稍后重试（错误码：\(initResult)）"
            self.loginButton.isEnabled = true
            return
        }
        
        self.statusLabel.text = "正在登录..."
        
        // 使用新的登录方法
        PhoneService.shared.loginWithAccount(
            account: account,
            password: password ?? "",
            environment: environment,
            passwordPk: passwordPk,
            statusUpdate: { [weak self] status in
                DispatchQueue.main.async {
                    self?.statusLabel.text = status
                }
            },
            success: { [weak self] _ in
                DispatchQueue.main.async {
                    guard let self = self else { return }
                    // 状态将由通知回调更新为连接成功
                    self.statusLabel.text = "正在建立连接..."
                }
            },
            failure: { [weak self] code, message in
                DispatchQueue.main.async {
                    guard let self = self else { return }
                    let readable = ErrorMessageProvider.loginErrorMessage(code: code, underlyingMessage: message)
                    self.statusLabel.text = "登录失败：\(readable)"
                    self.loginButton.isEnabled = true
                }
            }
        )
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

