//
//  ViewController.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 05/05/25.
//

import UIKit
import WebKit
import CoreBluetooth
import CoreLocation

@objc(StartConnectionViewController)
class StartConnectionViewController: UIViewController {

    @IBOutlet weak var customTopView: CustomTopUIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var startConnectionJourneyButton: CustomOverlayButton!
    
    
   // @objc var isForReconnect: Bool = false
    var webView: WKWebView!
    // Declare the CBCentralManager
    var centralManager: CBCentralManager?
    var isBluetoothEnabled: Bool = false
    
    // Declare the CLLocationManager
    var locationManager: CLLocationManager?
    var isLocationEnabled: Bool = false
    
    enum enumTableRow: Int, CaseIterable {
        case separator
        case verticalLabel
        case image
        case chargingIndicator
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupLayout()
        //checkForDevice()
    }
    
    func setupLayout() {
        navigationController?.navigationBar.isHidden = true
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerNibs([VerticalLabelsTVC.self,
                                SeparatorTVC.self,
                                ImageTVC.self,
                                ChargingIndicatorTVC.self])
        tableView.reloadData()
     
        let payload = [
            "status": "cgm_start_connection_landing"
        ]

        NotificationCenter.default.post(
            name: Notification.Name("cgmstartconnectionlanding"),
            object: nil,
            userInfo: payload
        )
        
        let isForReconnect = UserDefaults.standard.bool(forKey: "isForReconnect")
        if isForReconnect{
            checkLocationPermission()
            centralManager = CBCentralManager(delegate: self, queue: nil)
            // If the switch is turned on, check if Bluetooth is powered on
            checkBluetoothPermission()
            startConnectionJourneyButton.labelText = "Start Reconnection Journey"
        } else {
            startConnectionJourneyButton.labelText = "Start Connection Journey"
        }
        
        startConnectionJourneyButton.buttonTapCallback = {
            if isForReconnect {
                self.updateBottomButtonState()
            } else {
                let payload = [
                    "status": "cgm_start_connection_journey_clicked"
                ]

                NotificationCenter.default.post(
                    name: Notification.Name("cgmstartconnectionjourneyclicked"),
                    object: nil,
                    userInfo: payload
                )
                
                let vc = ProvidePermissionViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
                self.navigationController?.pushViewController(vc, animated: false)
            }
        }

        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 // or .pageSheet, .fullScreen
            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)
        }
    }
    
    private func updateBottomButtonState() {
        if isBluetoothEnabled && isLocationEnabled {
            let isForReconnect = UserDefaults.standard.bool(forKey: "isForReconnect")
            let vc = ConnectToTransmitterViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            vc.isForReconnect = isForReconnect
            self.navigationController?.pushViewController(vc, animated: false)
        } else {
            let vc = ProvidePermissionViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    
    private func checkBluetoothPermission() {
        isBluetoothEnabled = false
        switch centralManager?.state {
        case .unknown:
            print("Bluetooth state is unknown.")
        case .resetting:
            print("Bluetooth state is resetting.")
        case .unsupported:
            print("Bluetooth is unsupported on this device.")
        case .unauthorized:
            print("Bluetooth is unauthorized.")
        case .poweredOff:
            print("Bluetooth is powered off.")
        case .poweredOn:
            print("Bluetooth is powered on and available.")
            isBluetoothEnabled = true
        case .none:
            print("Unknown Bluetooth state.")
        @unknown default:
            print("Unknown Bluetooth state.")
        }
    }

    // Function to check Location Permission and State
    private func checkLocationPermission() {
        // Check if location services are enabled
        
        let status = CLLocationManager.authorizationStatus()
        
        switch status {
        case .notDetermined:
            print("Location permission is not determined.")
            // Request permission to use location services
            locationManager?.requestWhenInUseAuthorization()
        case .restricted, .denied:
            print("Location permission is restricted or denied.")
        case .authorizedWhenInUse, .authorizedAlways:
            print("Location is authorized.")
            isLocationEnabled = true
        @unknown default:
            print("Unknown location status.")
        }
    }

    func checkForDevice() {
        let manager = KLTBluetoothManager.shared()
        let currentDevice = manager?.currentDevice
     
        if (currentDevice != nil) {
            let eDevice : EDevice = EDevice.getEnumDevice(currentDevice?.advertise?.localName ?? "")
            let viewModel = FinalViewModel()
            viewModel.initialPeriod = Int(eDevice.initNumber * 3 * 60)
  
            let vc = AttachTransmitterViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            vc.viewModel = viewModel
            self.navigationController?.pushViewController(vc, animated: false)
        } else {
            // 未连接任何发射器
            // stay on this screen
        }
    }
}

extension StartConnectionViewController: 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 .image:
            return 205
        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 = "STEP1"
            cell.label1.isHidden = true
            cell.label2.text = "Before Y﻿ou Start"
            cell.label3.text = "Make sure your transmitter is fully charged. Put it in the charging pod until the blinking white light turns blue. This takes about 15 minutes"
            return cell
        case .image:
            let cell: ImageTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.displayImageView.image = loadImage(named: "charging_pod")
            return cell
        case .chargingIndicator:
            let cell: ChargingIndicatorTVC = tableView.dequeueReusableCell(for: indexPath)
            return cell
        }
    }
}


extension StartConnectionViewController: CBCentralManagerDelegate, CLLocationManagerDelegate {
    // Delegate method called when Bluetooth state changes
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        checkBluetoothPermission()
    }
}
