//
//  ProvidePermissionViewController.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 07/05/25.
//

import UIKit
import CoreBluetooth
import CoreLocation
class ProvidePermissionViewController: UIViewController {
    
    @IBOutlet weak var customTopView: CustomTopUIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var bottomButton: CustomOverlayButton!
    
    // Declare the CBCentralManager
    var centralManager: CBCentralManager?
    var isBluetoothEnabled: Bool = false
    let isForReconnect = UserDefaults.standard.bool(forKey: "isForReconnect")
    // Declare the CLLocationManager
    var locationManager: CLLocationManager?
    var isLocationEnabled: Bool = false
    
    enum enumTableRow: Int, CaseIterable {
        case separator
        case verticalLabel
        case bluetooth
        case location
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupLayout()
    }
    
    func setupLayout() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerNibs([VerticalLabelsTVC.self,
                                SeparatorTVC.self,
                                SwitchTVC.self])
        tableView.reloadData()
        
        bottomButton.labelText = "Proceed"
        bottomButton.buttonTapCallback = {
            
            let payload = [
                "status": "cgm_permissions_proceed_clicked",
                "bluetooth_toggle_status": self.isBluetoothEnabled == true ? "ON" : "OFF",
                "location_toggle_status": self.isLocationEnabled == true ? "ON" : "OFF"
            ]

            NotificationCenter.default.post(
                name: Notification.Name("cgmpermissionsproceedclicked"),
                object: nil,
                userInfo: payload
            )
            
            
            let vc = ConnectToTransmitterViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            vc.isForReconnect = self.isForReconnect
            self.navigationController?.pushViewController(vc, animated: false)
        }
        
        let payload = [
            "status": "cgm_start_connection_journey_clicked"
        ]

        NotificationCenter.default.post(
            name: Notification.Name("cgmpermissionspagelanding"),
            object: nil,
            userInfo: payload
        )
        
        customTopView.onDemoTapped = {
            
            let payload = [
                "status": "cgm_permissions_page_landing"
            ]
            
            NotificationCenter.default.post(
                name: Notification.Name("cgmwatchdemoclicked"),
                object: nil,
                userInfo: payload
            )
            let webVC = WebViewController()
            webVC.modalPresentationStyle = .formSheet
            webVC.videoURL = URL(string: self.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)
        }
        updateBottomButtonState()
        
        // Initialize the CBCentralManager with the current view controller as the delegate
        centralManager = CBCentralManager(delegate: self, queue: nil)
        // If the switch is turned on, check if Bluetooth is powered on
        checkBluetoothPermission()
        
        // Initialize the CLLocationManager
        locationManager = CLLocationManager()
        locationManager?.delegate = self
        locationManager?.requestWhenInUseAuthorization()
        // Check location permission on view load
        checkLocationPermission()
    }
    
    private func updateBottomButtonState() {
        if isBluetoothEnabled && isLocationEnabled {
            bottomButton.enable()
        } else {
            bottomButton.disable()
        }
    }
    
    // Show an alert to the user if Bluetooth is turned off or unauthorized
    private func showBluetoothPermissionAlert() {
        let alertController = UIAlertController(
            title: "Bluetooth Permission Required",
            message: "Please enable Bluetooth in Settings to use this feature.",
            preferredStyle: .alert
        )
        
        // Open Settings action
        alertController.addAction(UIAlertAction(title: "Open Settings", style: .default, handler: { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsURL)
            }
        }))
        
        // Cancel action
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    // Function to check Bluetooth Permission and State
    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.")
            showBluetoothPermissionAlert()
        case .poweredOff:
            print("Bluetooth is powered off.")
            showBluetoothPermissionAlert()
        case .poweredOn:
            print("Bluetooth is powered on and available.")
            isBluetoothEnabled = true
        case .none:
            print("Unknown Bluetooth state.")
        @unknown default:
            print("Unknown Bluetooth state.")
        }
        tableView.reloadData()
    }
    
    // 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.")
            showLocationPermissionAlert()
        case .authorizedWhenInUse, .authorizedAlways:
            print("Location is authorized.")
            isLocationEnabled = true
            tableView.reloadData()
        @unknown default:
            print("Unknown location status.")
        }
        
    }
    
    // Show an alert to the user if location services are off or permission is denied
    private func showLocationPermissionAlert() {
        let alertController = UIAlertController(
            title: "Location Permission Required",
            message: "Please enable Location Services in Settings to use this feature.",
            preferredStyle: .alert
        )
        
        // Open Settings action
        alertController.addAction(UIAlertAction(title: "Open Settings", style: .default, handler: { _ in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsURL)
            }
        }))
        
        // Cancel action
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    // Function to handle the switch's state change
    @objc func bluetoothSwitchChanged(_ sender: UISwitch) {
        if sender.isOn {
            // Initialize the CBCentralManager with the current view controller as the delegate
            centralManager = CBCentralManager(delegate: self, queue: nil)
            // If the switch is turned on, check if Bluetooth is powered on
            checkBluetoothPermission()
        } else {
            // If the switch is turned off, simply turn off Bluetooth
            print("Bluetooth switch turned off.")
            // You can add additional code here to handle the case where the user wants to turn off Bluetooth
        }
        updateBottomButtonState()
    }
    
    // Function to handle the switch's state change
    @objc func locationSwitchChanged(_ sender: UISwitch) {
        if sender.isOn {
            // Initialize the CLLocationManager
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            locationManager?.requestWhenInUseAuthorization()
            // Check location permission on view load
            checkLocationPermission()
            
            // If the switch is turned on, check if location permission is granted
            //checkLocationPermission()
        } else {
            // If the switch is turned off, stop updating location (or you can handle differently)
            locationManager?.stopUpdatingLocation()
            print("Location switch turned off.")
        }
        updateBottomButtonState()
    }
    
    @objc func showTrouble(_ sender: UIButton) {
        let vc = BluetoothConnectionViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
        vc.modalPresentationStyle = .overFullScreen
        self.present(vc, animated: true, completion: nil)
    }
}

extension ProvidePermissionViewController: 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) {
        default:
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        updateBottomButtonState()
        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 1"
            cell.label2.text = "Provide permissions"
            cell.label3.text = "GoodFlip CGM requires a bluetooth connection and location permission to transmit data to the app"
            return cell
        case .bluetooth:
            let cell: SwitchTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.labelTurnOn.text = "Turn on Bluetooth"
            cell.viewTrouble.isHidden = false
            cell.switchUI.addTarget(self, action: #selector(bluetoothSwitchChanged(_:)), for: .valueChanged)
            cell.switchUI.isOn = isBluetoothEnabled
            cell.buttonTrouble.addTarget(self, action: #selector(showTrouble(_:)), for: .touchUpInside)
            return cell
        case .location:
            let cell: SwitchTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.labelTurnOn.text = "Turn on Location"
            cell.viewTrouble.isHidden = true
            cell.switchUI.addTarget(self, action: #selector(locationSwitchChanged(_:)), for: .valueChanged)
            cell.switchUI.isOn = isLocationEnabled
            return cell
        }
    }
}
extension ProvidePermissionViewController: CBCentralManagerDelegate, CLLocationManagerDelegate {
    
    // Delegate method called when Bluetooth state changes
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        checkBluetoothPermission()
    }
    
    // CLLocationManagerDelegate method to handle when location permissions are changed
    /*func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationPermission()
    }*/
    // Handle location updates
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // Get the most recent location
        guard let location = locations.last else { return }
        
        // Print the latitude and longitude
        print("Latitude: \(location.coordinate.latitude), Longitude: \(location.coordinate.longitude)")
        
        // Optionally stop updating location after getting the first location
        //locationManager?.stopUpdatingLocation()
    }
    
    // Handle location permission changes
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            // Start updating location when permission is granted
            locationManager?.startUpdatingLocation()
            isLocationEnabled = true
            tableView.reloadData()
        } else {
            if status == .denied {
                // Inform the user that location permission is needed
                showLocationPermissionAlert()
            }
        }
    }
}
