package de.hackernet.wireguardtv.ui

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.leanback.app.GuidedStepSupportFragment
import androidx.leanback.widget.GuidanceStylist
import androidx.leanback.widget.GuidedAction
import androidx.lifecycle.lifecycleScope
import de.hackernet.wireguardtv.R
import de.hackernet.wireguardtv.data.SettingsRepository
import de.hackernet.wireguardtv.data.TunnelRepository
import kotlinx.coroutines.launch

/**
 * Dialog für Tunnel-Aktionen (Verbinden/Trennen, Autostart, Löschen)
 */
class TunnelActionDialogFragment : GuidedStepSupportFragment() {

    companion object {
        private const val TAG = "TunnelActionDialog"
        private const val ARG_TUNNEL_ID = "tunnel_id"
        private const val ARG_TUNNEL_NAME = "tunnel_name"
        private const val ARG_IS_CONNECTED = "is_connected"

        private const val ACTION_CONNECT = 1L
        private const val ACTION_DISCONNECT = 2L
        private const val ACTION_AUTOSTART = 3L
        private const val ACTION_DELETE = 4L
        private const val ACTION_CANCEL = 5L

        fun newInstance(tunnelId: String, tunnelName: String, isConnected: Boolean): TunnelActionDialogFragment {
            return TunnelActionDialogFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_TUNNEL_ID, tunnelId)
                    putString(ARG_TUNNEL_NAME, tunnelName)
                    putBoolean(ARG_IS_CONNECTED, isConnected)
                }
            }
        }

        fun show(fragmentManager: androidx.fragment.app.FragmentManager, fragment: TunnelActionDialogFragment) {
            add(fragmentManager, fragment)
        }
    }

    private lateinit var settingsRepository: SettingsRepository
    private val tunnelId: String by lazy { arguments?.getString(ARG_TUNNEL_ID) ?: "" }
    private val tunnelName: String by lazy { arguments?.getString(ARG_TUNNEL_NAME) ?: "" }
    private val isConnected: Boolean by lazy { arguments?.getBoolean(ARG_IS_CONNECTED) ?: false }
    private var isAutostart: Boolean = false

    override fun onAttach(context: Context) {
        super.onAttach(context)
        settingsRepository = SettingsRepository.getInstance(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Prüfen ob dieser Tunnel als Autostart konfiguriert ist (synchron laden)
        kotlinx.coroutines.runBlocking {
            val settings = settingsRepository.getSettings()
            isAutostart = settings.defaultTunnelId == tunnelId && settings.autoConnectOnBoot
            Log.d(TAG, "onCreate: tunnelId=$tunnelId, defaultTunnelId=${settings.defaultTunnelId}, autoConnectOnBoot=${settings.autoConnectOnBoot}, isAutostart=$isAutostart")
        }
    }

    override fun onStart() {
        super.onStart()
        // Werte bei jedem Start neu aus DB laden
        lifecycleScope.launch {
            val settings = settingsRepository.getSettings()
            isAutostart = settings.defaultTunnelId == tunnelId && settings.autoConnectOnBoot
            Log.d(TAG, "onStart: tunnelId=$tunnelId, defaultTunnelId=${settings.defaultTunnelId}, autoConnectOnBoot=${settings.autoConnectOnBoot}, isAutostart=$isAutostart")

            // UI immer aktualisieren
            findActionById(ACTION_AUTOSTART)?.let { action ->
                action.isChecked = isAutostart
                action.description = if (isAutostart) "Aktiviert" else "Deaktiviert"
                notifyActionChanged(findActionPositionById(ACTION_AUTOSTART))
            }
        }
    }

    override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
        return GuidanceStylist.Guidance(
            tunnelName,
            if (isConnected) "Verbunden" else "Nicht verbunden",
            "Tunnel-Aktionen",
            null
        )
    }

    override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
        if (isConnected) {
            actions.add(GuidedAction.Builder(requireContext())
                .id(ACTION_DISCONNECT)
                .title("Trennen")
                .description("VPN-Verbindung beenden")
                .build())
        } else {
            actions.add(GuidedAction.Builder(requireContext())
                .id(ACTION_CONNECT)
                .title("Verbinden")
                .description("VPN-Verbindung aufbauen")
                .build())
        }

        // Autostart-Option (DEFAULT_CHECK_SET_ID für einzelne Checkbox)
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_AUTOSTART)
            .title("Autostart beim Boot")
            .description(if (isAutostart) "Aktiviert" else "Deaktiviert")
            .checkSetId(GuidedAction.DEFAULT_CHECK_SET_ID)
            .checked(isAutostart)
            .build())

        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_DELETE)
            .title("Löschen")
            .description("Tunnel dauerhaft entfernen")
            .build())

        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_CANCEL)
            .title("Abbrechen")
            .build())
    }

    override fun onGuidedActionClicked(action: GuidedAction) {
        when (action.id) {
            ACTION_CONNECT -> {
                (activity as? MainActivity)?.connectTunnel(tunnelId)
                parentFragmentManager.popBackStack()
            }
            ACTION_DISCONNECT -> {
                (activity as? MainActivity)?.disconnectTunnel()
                parentFragmentManager.popBackStack()
            }
            ACTION_AUTOSTART -> {
                // Toggle Autostart - Manuell toggeln da DEFAULT_CHECK_SET_ID
                isAutostart = !isAutostart
                action.isChecked = isAutostart
                Log.d(TAG, "Toggle Autostart: isAutostart=$isAutostart, tunnelId=$tunnelId")

                lifecycleScope.launch {
                    val currentSettings = settingsRepository.getSettings()
                    val newSettings = if (isAutostart) {
                        // Diesen Tunnel als Autostart setzen
                        currentSettings.copy(
                            autoConnectOnBoot = true,
                            defaultTunnelId = tunnelId
                        )
                    } else {
                        // Autostart deaktivieren
                        currentSettings.copy(
                            autoConnectOnBoot = false,
                            defaultTunnelId = null
                        )
                    }

                    Log.d(TAG, "Saving settings: autoConnectOnBoot=${newSettings.autoConnectOnBoot}, defaultTunnelId=${newSettings.defaultTunnelId}")
                    settingsRepository.updateSettings(newSettings)

                    // Verifizieren, dass es gespeichert wurde
                    val savedSettings = settingsRepository.getSettings()
                    Log.d(TAG, "Verified saved: autoConnectOnBoot=${savedSettings.autoConnectOnBoot}, defaultTunnelId=${savedSettings.defaultTunnelId}")

                    if (isAutostart) {
                        Toast.makeText(context, "Autostart aktiviert - Verbindung wird aufgebaut...", Toast.LENGTH_LONG).show()
                        // Tunnel sofort verbinden, damit VPN-Berechtigung erteilt wird
                        // (sonst funktioniert Autostart beim Boot nicht)
                        (activity as? MainActivity)?.connectTunnel(tunnelId)
                        // Dialog schließen damit aktualisierte Liste sichtbar wird
                        parentFragmentManager.popBackStack()
                    } else {
                        Toast.makeText(context, "Autostart deaktiviert", Toast.LENGTH_SHORT).show()
                        // UI aktualisieren
                        action.description = "Deaktiviert"
                        notifyActionChanged(findActionPositionById(ACTION_AUTOSTART))
                    }
                }
            }
            ACTION_DELETE -> {
                // Bestätigungs-Dialog anzeigen
                add(parentFragmentManager, TunnelDeleteConfirmFragment.newInstance(tunnelId, tunnelName))
            }
            ACTION_CANCEL -> {
                parentFragmentManager.popBackStack()
            }
        }
    }
}

/**
 * Bestätigungs-Dialog für das Löschen
 */
class TunnelDeleteConfirmFragment : GuidedStepSupportFragment() {

    companion object {
        private const val ARG_DEL_TUNNEL_ID = "del_tunnel_id"
        private const val ARG_DEL_TUNNEL_NAME = "del_tunnel_name"

        private const val ACTION_CONFIRM = 1L
        private const val ACTION_CANCEL = 2L

        fun newInstance(tunnelId: String, tunnelName: String): TunnelDeleteConfirmFragment {
            return TunnelDeleteConfirmFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_DEL_TUNNEL_ID, tunnelId)
                    putString(ARG_DEL_TUNNEL_NAME, tunnelName)
                }
            }
        }
    }

    private val tunnelId: String by lazy { arguments?.getString(ARG_DEL_TUNNEL_ID) ?: "" }
    private val tunnelName: String by lazy { arguments?.getString(ARG_DEL_TUNNEL_NAME) ?: "" }

    override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
        return GuidanceStylist.Guidance(
            "Tunnel löschen?",
            "\"$tunnelName\" wird dauerhaft entfernt.",
            "Bestätigung",
            null
        )
    }

    override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_CONFIRM)
            .title("Ja, löschen")
            .description("Tunnel dauerhaft entfernen")
            .build())

        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_CANCEL)
            .title("Abbrechen")
            .build())
    }

    override fun onGuidedActionClicked(action: GuidedAction) {
        when (action.id) {
            ACTION_CONFIRM -> {
                lifecycleScope.launch {
                    val mainActivity = activity as? MainActivity
                    val repository = TunnelRepository.getInstance(requireContext())

                    // Wenn Tunnel aktiv ist, erst trennen
                    if (repository.getActiveTunnelId() == tunnelId) {
                        mainActivity?.disconnectTunnel()
                        // Kurz warten bis VPN getrennt ist
                        kotlinx.coroutines.delay(500)
                    }

                    repository.deleteTunnel(tunnelId)

                    Toast.makeText(context, "Tunnel gelöscht", Toast.LENGTH_SHORT).show()

                    // Zurück zur Hauptansicht
                    parentFragmentManager.popBackStack()
                    parentFragmentManager.popBackStack()

                    // Liste aktualisieren
                    mainActivity?.let {
                        val mainFragment = it.supportFragmentManager.findFragmentById(android.R.id.content) as? MainFragment
                        mainFragment?.refreshTunnelList()
                    }
                }
            }
            ACTION_CANCEL -> {
                parentFragmentManager.popBackStack()
            }
        }
    }
}
