//
//  AttachTransmitterViewController.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 08/05/25.
//

import UIKit

class AttachTransmitterViewController: UIViewController {

    @IBOutlet weak var customTopView: CustomTopUIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var bottomButton: CustomOverlayButton!
    @IBOutlet weak var previousButton: CustomOverlayButton!
    
    enum enumTableRow: Int, CaseIterable {
        case separator
        case verticalLabel
        case video
    }
    
    var viewModel = FinalViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupLayout()
        viewModel.initialize()
    }
    
    func setupLayout() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerNibs([VerticalLabelsTVC.self,
                                SeparatorTVC.self,
                                VideoTVC.self])
        tableView.reloadData()
        
        previousButton.labelText = "Previous"
        previousButton.setBorderOnly()
        previousButton.showLeftArrow()
        previousButton.buttonTapCallback = {
            self.navigationController?.popViewController(animated: true)
        }
        
        
        let payload = [
            "status": "cgm_place_transmitter_landing",
        ]

        NotificationCenter.default.post(
            name: Notification.Name("cgmplacetransmitterlanding"),
            object: nil,
            userInfo: payload
        )
        
        bottomButton.labelText = "Complete"
        bottomButton.buttonTapCallback = {
            let payload = [
                "status": "cgm_connection_complete_clicked",
            ]

            NotificationCenter.default.post(
                name: Notification.Name("cgmconnectioncompleteclicked"),
                object: nil,
                userInfo: payload
            )
            
            
            let data = KLTDatabaseHandler.shared().queryAllReceiveData() as! [ReceiveData]
            print("===> all data count: ", data.count)
//            KLTDatabaseHandler.shared().reloadQueryHistoryData()
            
            if let device = KLTBluetoothManager.shared().currentDevice {
                let arrayFromInitial = KLTDatabaseHandler.shared().queryGlucoseData(with: device) as! [GlucoseData]
                print(arrayFromInitial)
                print("===> arrayFromInitial count: ", arrayFromInitial.count)
                
                self.viewModel.uploadData(data: arrayFromInitial)
            }
            
            NotificationCenter.default.post(name: Notification.Name("cgmDeviceEvent"), object: nil, userInfo: ["a":"a"])
            if let rootVC = UIApplication.shared.connectedScenes
                .compactMap({ ($0 as? UIWindowScene)?.windows.first?.rootViewController })
                .first {
                rootVC.dismiss(animated: true, completion: nil)
            } else if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
                rootViewController.dismiss(animated: true, completion: nil)
            }
            
            //let vc = ConnectToTransmitterViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            //self.navigationController?.pushViewController(vc, animated: true)
        }

        customTopView.onDemoTapped = {
            let isForReconnect = UserDefaults.standard.bool(forKey: "isForReconnect")
            let payload = [
                "status": "cgm_watch_demo_clicked"
            ]
            
            NotificationCenter.default.post(
                name: Notification.Name("cgmwatchdemoclicked"),
                object: nil,
                userInfo: payload
            )
            
            let webVC = WebViewController()
            webVC.modalPresentationStyle = .formSheet
            webVC.videoURL = URL(string: isForReconnect == true ? reconnectionwatchCGMVideo : watchCGMVideo)
            self.present(webVC, animated: true, completion: nil)
        }
        customTopView.onCloseTapped = {
            let vc = ExitJourneyViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            vc.modalPresentationStyle = .overFullScreen
            self.present(vc, animated: true, completion: nil)
        }
        customTopView.onWhatsAppTapped = {
            let vc = ChatWithExpertViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }

}

extension AttachTransmitterViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return enumTableRow.allCases.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch enumTableRow(rawValue: indexPath.row) {
        case .video:
            return 272
        default:
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch enumTableRow(rawValue: indexPath.row)! {
        case .separator:
            let cell: SeparatorTVC = tableView.dequeueReusableCell(for: indexPath)
            return cell
        case .verticalLabel:
            let cell: VerticalLabelsTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.label1.text = "STEP 5"
            cell.label2.text = "Attach the transmitter"
            cell.label3.text = "Watch the below video or follow the steps to attach the transmitter"
            return cell
        case .video:
            let cell: VideoTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.imageViewBackground.image = loadImage(named: "step5")
            cell.onPlayVideo = {
                let webVC = WebViewController()
                webVC.modalPresentationStyle = .formSheet
                webVC.videoURL = URL(string: applyingTheTransmitter)
                self.present(webVC, animated: true, completion: nil)
            }
            return cell
        }
    }
}
