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

import UIKit

class PhoneMainViewController: UIViewController {
    
    private let accountTextField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "账号"
        tf.borderStyle = .roundedRect
        tf.autocapitalizationType = .none
        tf.autocorrectionType = .no
        tf.keyboardType = .default
        return tf
    }()
    
    private let passwordTextField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "密码"
        tf.borderStyle = .roundedRect
        tf.isSecureTextEntry = true
        tf.autocapitalizationType = .none
        tf.autocorrectionType = .no
        return tf
    }()
    
    private let passwordPkTextField: UITextField = {
        let tf = UITextField()
        tf.placeholder = "秘钥（可选，如果填写则使用秘钥登录）"
        tf.borderStyle = .roundedRect
        tf.autocapitalizationType = .none
        tf.autocorrectionType = .no
        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 button = UIBarButtonItem(
            title: "导出日志",
            style: .plain,
            target: self,
            action: #selector(exportLogButtonTapped)
        )
        navigationItem.rightBarButtonItem = button
    }
    
    @objc private func exportLogButtonTapped() {
        // 获取日志文件路径
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let logDirectory = documentsPath.appendingPathComponent("VoIPLogs")
        let voipLogPath = logDirectory.appendingPathComponent("voip.log")
        let pjsipLogPath = logDirectory.appendingPathComponent("voip_pjsip.log")
        
        // 收集存在的日志文件
        var logFiles: [URL] = []
        
        if FileManager.default.fileExists(atPath: voipLogPath.path) {
            logFiles.append(voipLogPath)
        }
        
        if FileManager.default.fileExists(atPath: pjsipLogPath.path) {
            logFiles.append(pjsipLogPath)
        }
        
        // 检查是否有日志文件存在
        guard !logFiles.isEmpty else {
            let alert = UIAlertController(
                title: "日志导出",
                message: "当前没有可导出的日志文件。",
                preferredStyle: .alert
            )
            alert.addAction(UIAlertAction(title: L.General.ok, style: .default))
            present(alert, animated: true)
            return
        }
        
        // 创建分享控制器，可以同时分享多个文件
        let activityVC = UIActivityViewController(
            activityItems: logFiles,
            applicationActivities: nil
        )
        
        // iPad 支持
        if let popover = activityVC.popoverPresentationController {
            popover.barButtonItem = navigationItem.rightBarButtonItem
        }
        
        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: -120),
            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.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)
    }
    
    @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
            
            // 登录成功后，自动跳转到拨号页面
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                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)
    }
}

