//
//  CallSettingsViewController.swift
//  JJPhoneDemo
//
//  通话设置页面 - 管理外显号码和号码组
//

import UIKit

class CallSettingsViewController: UIViewController {
    
    private let voipManager = VoIPManager.shared()
    
    // 数据模型
    private var callerStrategy: [String] = []  // 外显策略，如 ["enterpriseGroup"] 或 ["enterprise"]
    private var displayNumbers: [[String: Any]] = []  // 外显号码列表
    private var displayNumberGroups: [[String: Any]] = []  // 外显号码组列表
    private var currentSelectNumber: String?  // 当前选择的外显号码
    private var currentNumberGroup: String?  // 当前选择的号码组ID
    private var loadingFlags: (groups: Bool, numbers: Bool) = (false, false)  // 加载状态标记
    
    // 原始值（用于检测是否有改动）
    private var originalSelectNumber: String?  // 原始选择的外显号码
    private var originalNumberGroup: String?  // 原始选择的号码组ID
    
    // 是否有未保存的改动
    private var hasUnsavedChanges: Bool {
        // 比较两个可选字符串值是否相等
        let numberChanged = (currentSelectNumber ?? "") != (originalSelectNumber ?? "")
        let groupChanged = (currentNumberGroup ?? "") != (originalNumberGroup ?? "")
        return numberChanged || groupChanged
    }
    
    // UI 组件
    private let loadingIndicator: UIActivityIndicatorView = {
        let indicator: UIActivityIndicatorView
        if #available(iOS 13.0, *) {
            indicator = UIActivityIndicatorView(style: .medium)
        } else {
            indicator = UIActivityIndicatorView(style: .gray)
        }
        indicator.translatesAutoresizingMaskIntoConstraints = false
        indicator.hidesWhenStopped = true
        return indicator
    }()
    
    // 固定的 section header 视图（不随滚动）
    private let fixedHeaderLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.font = .systemFont(ofSize: 13, weight: .medium)
        if #available(iOS 13.0, *) {
            label.textColor = .secondaryLabel
            label.backgroundColor = .systemGroupedBackground
        } else {
            label.textColor = .gray
            label.backgroundColor = .groupTableViewBackground
        }
        // 设置文本左边距，与列表内容对齐
        label.textAlignment = .left
        return label
    }()
    
    private let tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .plain)
        tv.translatesAutoresizingMaskIntoConstraints = false
        tv.separatorStyle = .singleLine
        tv.separatorInset = .zero
        tv.layoutMargins = .zero
        tv.cellLayoutMarginsFollowReadableWidth = false
        tv.contentInsetAdjustmentBehavior = .never
        return tv
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "通话设置"
        if #available(iOS 13.0, *) {
            view.backgroundColor = .systemGroupedBackground
        } else {
            view.backgroundColor = .groupTableViewBackground
        }
        
        // 添加右上角保存按钮（对号图标）
        let saveButton: UIBarButtonItem
        if #available(iOS 13.0, *) {
            saveButton = UIBarButtonItem(
                image: UIImage(systemName: "checkmark"),
                style: .plain,
                target: self,
                action: #selector(saveButtonTapped)
            )
        } else {
            saveButton = UIBarButtonItem(
                title: "保存",
                style: .plain,
                target: self,
                action: #selector(saveButtonTapped)
            )
        }
        navigationItem.rightBarButtonItem = saveButton
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        // 自定义返回按钮，用于拦截返回操作
        let backButton: UIBarButtonItem
        if #available(iOS 13.0, *) {
            backButton = UIBarButtonItem(
                image: UIImage(systemName: "chevron.left"),
                style: .plain,
                target: self,
                action: #selector(backButtonTapped)
            )
        } else {
            backButton = UIBarButtonItem(
                title: "返回",
                style: .plain,
                target: self,
                action: #selector(backButtonTapped)
            )
        }
        navigationItem.leftBarButtonItem = backButton
        
        setupUI()
        loadData()
    }
    
    @objc private func backButtonTapped() {
        if hasUnsavedChanges {
            // 有未保存的改动，显示提示
            checkUnsavedChanges()
        } else {
            // 没有改动，直接返回
            navigationController?.popViewController(animated: true)
        }
    }
    
    private func setupUI() {
        view.addSubview(tableView)
        view.addSubview(fixedHeaderLabel)
        view.addSubview(loadingIndicator)
        
        tableView.dataSource = self
        tableView.delegate = self
        
        // 设置 tableView 的内容偏移，为固定 header 留出空间
        tableView.contentInset = UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)
        tableView.scrollIndicatorInsets = UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)
        
        NSLayoutConstraint.activate([
            // 固定 Header Label（在顶部左侧，不随滚动，与列表内容对齐）
            fixedHeaderLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            fixedHeaderLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
            fixedHeaderLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            fixedHeaderLabel.heightAnchor.constraint(equalToConstant: 40),
            
            // Loading Indicator（居中显示）
            loadingIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            loadingIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            
            // TableView 全屏显示（在安全区域内）
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
    
    private func loadData() {
        loadingIndicator.startAnimating()
        fixedHeaderLabel.isHidden = true
        
        // 1. 先获取外显策略
        voipManager.getCallerStrategy(
            success: { [weak self] config in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    // 解析配置信息
                    if let strategy = config["callerStrategy"] as? [String] {
                        self.callerStrategy = strategy
                    }
                    
                    // 保存原始值（无论是否存在都要初始化）
                    if let selectNumber = config["selectNumber"] as? String, !selectNumber.isEmpty {
                        self.currentSelectNumber = selectNumber
                        self.originalSelectNumber = selectNumber
                    } else {
                        self.currentSelectNumber = nil
                        self.originalSelectNumber = nil
                    }
                    
                    if let numberGroup = config["numberGroup"] as? String, !numberGroup.isEmpty {
                        self.currentNumberGroup = numberGroup
                        self.originalNumberGroup = numberGroup
                    } else {
                        self.currentNumberGroup = nil
                        self.originalNumberGroup = nil
                    }
                    
                    // 根据外显策略加载相应的数据
                    self.loadDisplayData()
                }
            },
            failure: { [weak self] code, message in
                DispatchQueue.main.async {
                    self?.loadingIndicator.stopAnimating()
                    self?.showErrorAlert(message: message)
                }
            }
        )
    }
    
    private func loadDisplayData() {
        // 判断外显策略：如果包含 "enterpriseGroup"，显示号码组列表；如果包含 "enterprise"，显示号码列表
        let showGroups = callerStrategy.contains("enterpriseGroup")
        let showNumbers = callerStrategy.contains("enterprise")
        
        // 重置加载标记（true 表示正在加载，false 表示加载完成）
        loadingFlags = (showGroups, showNumbers)
        
        if showGroups && showNumbers {
            // 两个都显示
            loadNumberGroups()
            loadNumbers()
        } else if showGroups {
            // 只显示号码组
            loadNumberGroups()
        } else if showNumbers {
            // 只显示号码列表
            loadNumbers()
        } else {
            // 无外显策略
            loadingIndicator.stopAnimating()
            fixedHeaderLabel.isHidden = true
            tableView.isHidden = true
            showErrorAlert(message: "当前账号无外显策略配置")
        }
    }
    
    private func loadNumberGroups() {
        voipManager.getDisplayNumberGroupList(
            success: { [weak self] groupList in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    // 转换为数组
                    var groups: [[String: Any]] = []
                    for item in groupList {
                        if let dict = item as? [String: Any] {
                            groups.append(dict)
                        }
                    }
                    self.displayNumberGroups = groups
                    
                    // 标记加载完成
                    self.loadingFlags.groups = false
                    
                    // 检查是否所有数据都已加载完成
                    if !self.loadingFlags.numbers {
                        self.refreshUI()
                    }
                }
            },
            failure: { [weak self] code, message in
                DispatchQueue.main.async {
                    guard let self = self else { return }
                    AppLogger.error("Failed to get number groups - code: \(code), message: \(message)", category: "CallSettings")
                    
                    // 标记加载完成（失败也算完成）
                    self.loadingFlags.groups = false
                    
                    // 检查是否所有数据都已加载完成
                    if !self.loadingFlags.numbers {
                        self.loadingIndicator.stopAnimating()
                        if self.displayNumberGroups.isEmpty && self.displayNumbers.isEmpty {
                            self.showErrorAlert(message: "加载失败: \(message)")
                        } else {
                            self.refreshUI()
                        }
                    }
                }
            }
        )
    }
    
    private func loadNumbers() {
        voipManager.getDisplayNumberList(
            success: { [weak self] numberList in
                guard let self = self else { return }
                
                DispatchQueue.main.async {
                    // 转换为数组
                    var numbers: [[String: Any]] = []
                    for item in numberList {
                        if let dict = item as? [String: Any] {
                            numbers.append(dict)
                        }
                    }
                    self.displayNumbers = numbers
                    
                    // 标记加载完成
                    self.loadingFlags.numbers = false
                    
                    // 检查是否所有数据都已加载完成
                    if !self.loadingFlags.groups {
                        self.refreshUI()
                    }
                }
            },
            failure: { [weak self] code, message in
                DispatchQueue.main.async {
                    guard let self = self else { return }
                    AppLogger.error("Failed to get numbers - code: \(code), message: \(message)", category: "CallSettings")
                    
                    // 标记加载完成（失败也算完成）
                    self.loadingFlags.numbers = false
                    
                    // 检查是否所有数据都已加载完成
                    if !self.loadingFlags.groups {
                        self.loadingIndicator.stopAnimating()
                        if self.displayNumberGroups.isEmpty && self.displayNumbers.isEmpty {
                            self.showErrorAlert(message: "加载失败: \(message)")
                        } else {
                            self.refreshUI()
                        }
                    }
                }
            }
        )
    }
    
    private func refreshUI() {
        loadingIndicator.stopAnimating()
        
        let totalCount = displayNumberGroups.count + displayNumbers.count
        if totalCount > 0 {
            // 显示固定 header 标签（优先显示号码组，因为号码组通常是第一个 section）
            let showGroups = callerStrategy.contains("enterpriseGroup") && !displayNumberGroups.isEmpty
            let showNumbers = callerStrategy.contains("enterprise") && !displayNumbers.isEmpty
            
            if showGroups {
                fixedHeaderLabel.text = "外显号码组"
            } else if showNumbers {
                fixedHeaderLabel.text = "外显号码"
            } else {
                fixedHeaderLabel.text = ""
            }
            fixedHeaderLabel.isHidden = false
            
            tableView.isHidden = false
            tableView.reloadData()
            navigationItem.rightBarButtonItem?.isEnabled = true
        } else {
            fixedHeaderLabel.isHidden = true
            tableView.isHidden = true
            showErrorAlert(message: "暂无可用的外显号码或号码组，请联系管理员配置。")
        }
    }
    
    private func checkUnsavedChanges() {
        guard hasUnsavedChanges else {
            navigationController?.popViewController(animated: true)
            return
        }
        
        let alert = UIAlertController(
            title: "未保存的更改",
            message: "您有未保存的设置更改，是否要保存？",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: L.General.cancel, style: .cancel) { _ in
            // 取消返回，继续停留在当前页面
        })
        
        alert.addAction(UIAlertAction(title: "不保存", style: .destructive) { [weak self] _ in
            // 不保存，直接返回
            self?.navigationController?.popViewController(animated: true)
        })
        
        alert.addAction(UIAlertAction(title: "保存", style: .default) { [weak self] _ in
            // 保存后返回
            self?.saveAndReturn()
        })
        
        present(alert, animated: true)
    }
    
    private func saveAndReturn() {
        let hasSelectedNumber = currentSelectNumber != nil
        let hasSelectedGroup = currentNumberGroup != nil
        
        if !hasSelectedNumber && !hasSelectedGroup {
            // 如果都没选择，直接返回
            navigationController?.popViewController(animated: true)
            return
        }
        
        // 显示加载状态
        let alert = UIAlertController(title: nil, message: "正在保存设置…", preferredStyle: .alert)
        present(alert, animated: true)
        
        voipManager.updateAgentDisplayNumber(
            withSelectNumber: currentSelectNumber,
            numberGroup: currentNumberGroup,
            success: { [weak self] in
                DispatchQueue.main.async {
                    alert.dismiss(animated: true) {
                        // 更新原始值
                        self?.originalSelectNumber = self?.currentSelectNumber
                        self?.originalNumberGroup = self?.currentNumberGroup
                        // 返回上一页
                        self?.navigationController?.popViewController(animated: true)
                    }
                }
            },
            failure: { [weak self] code, message in
                DispatchQueue.main.async {
                    alert.dismiss(animated: true) {
                        self?.showErrorAlert(message: "保存失败：\(message)")
                    }
                }
            }
        )
    }
    
    @objc private func saveButtonTapped() {
        guard navigationItem.rightBarButtonItem?.isEnabled == true else { return }
        
        let hasSelectedNumber = currentSelectNumber != nil
        let hasSelectedGroup = currentNumberGroup != nil
        
        if !hasSelectedNumber && !hasSelectedGroup {
            showErrorAlert(message: "请先选择要使用的外显号码或号码组。")
            return
        }
        
        // 显示加载状态
        let alert = UIAlertController(title: nil, message: "正在保存设置…", preferredStyle: .alert)
        present(alert, animated: true)
        
        voipManager.updateAgentDisplayNumber(
            withSelectNumber: currentSelectNumber,
            numberGroup: currentNumberGroup,
            success: { [weak self] in
                DispatchQueue.main.async {
                    alert.dismiss(animated: true) {
                        // 保存成功后，更新原始值
                        self?.originalSelectNumber = self?.currentSelectNumber
                        self?.originalNumberGroup = self?.currentNumberGroup
                        self?.showSuccessAlert(message: "设置已保存。")
                    }
                }
            },
            failure: { [weak self] code, message in
                DispatchQueue.main.async {
                    alert.dismiss(animated: true) {
                        self?.showErrorAlert(message: "保存失败：\(message)")
                    }
                }
            }
        )
    }
    
    private func showErrorAlert(message: String) {
        let alert = UIAlertController(title: L.CallSettings.titleError, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: L.General.ok, style: .default))
        present(alert, animated: true)
    }
    
    private func showSuccessAlert(message: String) {
        let alert = UIAlertController(title: L.CallSettings.titleSuccess, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: L.General.ok, style: .default))
        present(alert, animated: true)
    }
}

// MARK: - UITableViewDataSource
extension CallSettingsViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        var sections = 0
        if !displayNumberGroups.isEmpty && callerStrategy.contains("enterpriseGroup") {
            sections += 1
        }
        if !displayNumbers.isEmpty && callerStrategy.contains("enterprise") {
            sections += 1
        }
        return sections
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 && !displayNumberGroups.isEmpty && callerStrategy.contains("enterpriseGroup") {
            return displayNumberGroups.count
        } else {
            return displayNumbers.count
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        // 不显示 section header，因为已经在顶部固定显示了
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = (indexPath.section == 0 && !displayNumberGroups.isEmpty && callerStrategy.contains("enterpriseGroup")) ? "GroupCell" : "NumberCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier) ?? UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
        cell.selectionStyle = .default
        
        cell.contentView.layoutMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        
        var isSelected = false
        
        if indexPath.section == 0 && !displayNumberGroups.isEmpty && callerStrategy.contains("enterpriseGroup") {
            // 显示号码组
            let group = displayNumberGroups[indexPath.row]
            let groupName = group["groupName"] as? String ?? "未知组"
            let groupId = group["id"] as? String ?? ""
            let remark = group["remark"] as? String
            
            cell.textLabel?.text = groupName
            if let remark = remark, !remark.isEmpty {
                cell.detailTextLabel?.text = "备注: \(remark)"
            } else {
                cell.detailTextLabel?.text = "备注: 无"
            }
            if #available(iOS 13.0, *) {
                cell.detailTextLabel?.textColor = .secondaryLabel
            } else {
                // Fallback on earlier versions
            }
            // 设置 contentView 的左边距与标题对齐（0）
            cell.contentView.layoutMargins = .zero
            
            // 检查是否已选择
            isSelected = (currentNumberGroup == groupId)
        } else {
            // 显示号码
            let number = displayNumbers[indexPath.row]
            let numberStr = number["number"] as? String ?? "未知号码"
            let status = number["status"] as? String
            let city = number["city"] as? String
            let province = number["province"] as? String
            
            cell.textLabel?.text = numberStr
            var detailText = ""
            if let province = province, let city = city {
                detailText = "\(province) \(city)"
            } else if let city = city {
                detailText = city
            }
            if let status = status {
                if !detailText.isEmpty {
                    detailText += " | "
                }
                detailText += "状态: \(status)"
            }
            cell.detailTextLabel?.text = detailText.isEmpty ? nil : detailText
            if #available(iOS 13.0, *) {
                cell.detailTextLabel?.textColor = .secondaryLabel
            } else {
                // Fallback on earlier versions
            }
            
            // 检查是否已选择
            isSelected = (currentSelectNumber == numberStr)
        }
        
        cell.accessoryType = isSelected ? .checkmark : .none
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension CallSettingsViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 0 && !displayNumberGroups.isEmpty && callerStrategy.contains("enterpriseGroup") {
            // 选择号码组
            let group = displayNumberGroups[indexPath.row]
            let groupId = group["id"] as? String ?? ""
            
            if currentNumberGroup == groupId {
                // 取消选择
                currentNumberGroup = nil
            } else {
                // 选择新号码组
                currentNumberGroup = groupId
                currentSelectNumber = nil
            }
        } else {
            // 选择号码
            let number = displayNumbers[indexPath.row]
            let numberStr = number["number"] as? String ?? ""
            
            if currentSelectNumber == numberStr {
                // 取消选择
                currentSelectNumber = nil
            } else {
                // 选择新号码
                currentSelectNumber = numberStr
                currentNumberGroup = nil
            }
        }
        
        tableView.reloadData()
    }
}

