package com.obdwidgets.ui

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import androidx.preference.EditTextPreference
import android.text.InputType
import com.obdwidgets.R
import com.obdwidgets.service.OBDService
import com.obdwidgets.util.PermissionHelper
import android.os.Build
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class SettingsActivity : AppCompatActivity() {
    
    companion object {
        private const val PERMISSION_REQUEST_CODE = 100
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        
        checkPermissions()
        
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings, SettingsFragment())
                .commit()
        }
        
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    private fun checkPermissions() {
        val permissions = mutableListOf<String>()
        if (!PermissionHelper.hasBluetoothPermissions(this)) {
            permissions.addAll(PermissionHelper.getBluetoothPermissions())
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.POST_NOTIFICATIONS)
        }
        if (permissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissions.toTypedArray(), PERMISSION_REQUEST_CODE)
        }
    }
    
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                Toast.makeText(this, "Berechtigungen erteilt", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    class SettingsFragment : PreferenceFragmentCompat() {
        
        private val REQUEST_ENABLE_BT = 1
        private val PERMISSION_REQUEST_CODE_FRAGMENT = 200
        
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)
            setupBluetoothPreference()
            setupTestModePreference()
            setupAutoConnectPreference()
            setupReconnectIntervalPreference()
        }
        
        private fun setupBluetoothPreference() {
            val btPreference = findPreference<Preference>("bt_device")
            btPreference?.setOnPreferenceClickListener {
                handleBluetoothSelection()
                true
            }
            updateBluetoothDeviceSummary()
        }

        private fun handleBluetoothSelection() {
            val context = context ?: return
            
            // 1. Check Runtime Permissions
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(Manifest.permission.BLUETOOTH_CONNECT), PERMISSION_REQUEST_CODE_FRAGMENT)
                return
            }

            // 2. Get Bluetooth Adapter
            val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
            val bluetoothAdapter = bluetoothManager.adapter

            if (bluetoothAdapter == null) {
                Toast.makeText(context, "Gerät unterstützt kein Bluetooth", Toast.LENGTH_SHORT).show()
                return
            }

            // 3. Check if Enabled
            if (!bluetoothAdapter.isEnabled) {
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                @Suppress("DEPRECATION")
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
                return
            }

            showBluetoothDeviceDialog(bluetoothAdapter)
        }
        
        private fun showBluetoothDeviceDialog(adapter: BluetoothAdapter) {
            val context = context ?: return
            try {
                val pairedDevices = adapter.bondedDevices
                val deviceNames = mutableListOf<String>()
                val deviceAddresses = mutableListOf<String>()
                
                deviceNames.add("Kein Gerät ausgewählt")
                deviceAddresses.add("")
                
                pairedDevices?.forEach { device ->
                    deviceNames.add("${device.name ?: "Unbekannt"}\n${device.address}")
                    deviceAddresses.add(device.address)
                }
                
                android.app.AlertDialog.Builder(context)
                    .setTitle("Bluetooth Gerät wählen")
                    .setItems(deviceNames.toTypedArray()) { _, which ->
                        val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context)
                        if (which == 0) {
                            prefs.edit().remove("bt_device_address").apply()
                        } else {
                            prefs.edit().putString("bt_device_address", deviceAddresses[which]).apply()
                        }
                        updateBluetoothDeviceSummary()
                    }
                    .setNegativeButton("Abbrechen", null)
                    .show()
            } catch (e: SecurityException) {
                Toast.makeText(context, "Bluetooth-Berechtigung erforderlich", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Toast.makeText(context, "Fehler beim Laden der Geräte", Toast.LENGTH_SHORT).show()
            }
        }
        
        private fun updateBluetoothDeviceSummary() {
            val context = context ?: return
            val prefs = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context)
            val deviceAddress = prefs.getString("bt_device_address", null)
            val btPreference = findPreference<Preference>("bt_device")
            
            if (deviceAddress.isNullOrEmpty()) {
                btPreference?.summary = "Kein Gerät ausgewählt"
                return
            }

            try {
                val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
                val device = bluetoothManager.adapter?.getRemoteDevice(deviceAddress)
                
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                    btPreference?.summary = device?.name ?: deviceAddress
                } else {
                    btPreference?.summary = deviceAddress
                }
            } catch (e: Exception) {
                btPreference?.summary = deviceAddress
            }
        }
        
        private fun setupTestModePreference() {
            findPreference<SwitchPreferenceCompat>("test_mode")?.setOnPreferenceChangeListener { _, _ ->
                restartService()
                true
            }
        }
        
        private fun setupAutoConnectPreference() {
            findPreference<SwitchPreferenceCompat>("auto_connect")?.setOnPreferenceChangeListener { _, newValue ->
                if (newValue as Boolean) restartService() else context?.stopService(Intent(context, OBDService::class.java))
                true
            }
        }
        
        private fun restartService() {
            val intent = Intent(context, OBDService::class.java)
            context?.stopService(intent)
            context?.startForegroundService(intent)
        }

        private fun setupReconnectIntervalPreference() {
            findPreference<EditTextPreference>("reconnect_interval")?.setOnBindEditTextListener { it.inputType = InputType.TYPE_CLASS_NUMBER }
        }
        
        @Deprecated("Deprecated in Java")
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            @Suppress("DEPRECATION")
            super.onActivityResult(requestCode, resultCode, data)
            if (requestCode == REQUEST_ENABLE_BT && resultCode == android.app.Activity.RESULT_OK) {
                handleBluetoothSelection()
            }
        }
    }
}
