//
//  PDWifiHotspotsViewController.swift
//  PrinterDemo
//
//  Created by ios on 2025/1/16.
//  Copyright © 2025 XiamenHY. All rights reserved.
//

import UIKit
import PrinterSDK
import SVProgressHUD

class PDWifiHotspotsViewController: PDBaseViewController {
    
    private var tableView: UITableView!
    private var hotspots: [WifiHotspotInfo] = []
    private var refreshControl: UIRefreshControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        loadWifiHotspots()
    }
    
    private func setupUI() {
        title = "可用的WiFi热点".localized
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "刷新".localized,
            style: .plain,
            target: self,
            action: #selector(refreshButtonTapped)
        )
        
        // 创建TableView
        tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 80
        tableView.separatorStyle = .singleLine
        view.addSubview(tableView)
        
        // 设置约束
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 添加下拉刷新
        refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(refreshButtonTapped), for: .valueChanged)
        if #available(iOS 10.0, *) {
            tableView.refreshControl = refreshControl
        } else {
            // Fallback on earlier versions
        }
    }
    
    @objc private func cancelButtonTapped() {
        dismiss(animated: true)
    }
    
    @objc private func refreshButtonTapped() {
        loadWifiHotspots()
    }
    
    private func loadWifiHotspots() {
        guard let printer = PrinterManager.instance.accessory, printer.connected else {
            SVProgressHUD.showError(withStatus: "打印机未连接".localized)
            return
        }
        
        SVProgressHUD.show(withStatus: "正在获取WiFi热点列表...".localized)
        
        printer.getWifiHotspots { [weak self] (datas, error) in
            if let error = error{
                SVProgressHUD.showError(withStatus: "获取WiFi热点失败: \(error.localizedDescription)")
                return
            }
            let hotspots = WifiHotspotInfo.parseWifiHotspotsData(datas ?? Data())
            SVProgressHUD.dismiss()
            self?.refreshControl.endRefreshing()
            
            self?.hotspots = hotspots
            self?.tableView.reloadData()
            
            if hotspots.isEmpty {
                SVProgressHUD.showInfo(withStatus: "未找到可用的WiFi热点".localized)
            }
        }
    }
}

// MARK: - UITableViewDataSource
extension PDWifiHotspotsViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return hotspots.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "WifiHotspotCell")
        if cell == nil{
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: "WifiHotspotCell")
        }
        guard let cell = cell else { return UITableViewCell() }
        let hotspot = hotspots[indexPath.row]
        
        // 配置cell
        cell.textLabel?.text = hotspot.name
        cell.textLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        
        // 详细信息
        let detailText = "\(hotspot.security) / \(hotspot.encryption)"
        cell.detailTextLabel?.text = detailText
        cell.detailTextLabel?.font = UIFont.systemFont(ofSize: 14)
        cell.detailTextLabel?.textColor = .gray
        
        // 信号强度显示
        if let signalValue = Int(hotspot.signalStrength) {
            let signalText = "\(signalValue) dBm"
            cell.accessoryType = .disclosureIndicator
            
            // 根据信号强度设置颜色
            if signalValue >= -50 {
                cell.textLabel?.textColor = .systemGreen
            } else if signalValue >= -60 {
                cell.textLabel?.textColor = .systemBlue
            } else if signalValue >= -70 {
                cell.textLabel?.textColor = .systemOrange
            } else {
                cell.textLabel?.textColor = .systemRed
            }
            
            // 在detailTextLabel中显示信号强度
            cell.detailTextLabel?.text = "\(detailText) • \(signalText)"
        } else {
            if #available(iOS 13.0, *) {
                cell.textLabel?.textColor = .label
            } else {
                // Fallback on earlier versions
            }
            cell.accessoryType = .none
        }
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension PDWifiHotspotsViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let hotspot = hotspots[indexPath.row]
        
        // 显示热点详情
        let alert = UIAlertController(
            title: hotspot.name,
            message: """
            加密协议: \(hotspot.security)
            加密类型: \(hotspot.encryption)
            信号强度: \(hotspot.signalStrength) dBm
            """,
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "确定".localized, style: .default))
        present(alert, animated: true)
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return hotspots.isEmpty ? nil : "找到 \(hotspots.count) 个WiFi热点"
    }
}
