package de.hackernet.wireguardtv.ui
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
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 kotlinx.coroutines.launch

/**
 * Dialog für WebServer Aktionen (Start/Stop/Konfiguration)
 */
class WebServerActionDialogFragment : GuidedStepSupportFragment() {

    private var isRunning: Boolean = false
    private var serverIp: String? = null
    private lateinit var settingsRepository: SettingsRepository

    companion object {
        private const val ARG_IS_RUNNING = "is_running"
        private const val ARG_SERVER_IP = "server_ip"

        private const val ACTION_START = 1L
        private const val ACTION_STOP = 2L
        private const val ACTION_SETTINGS = 3L
        private const val ACTION_CANCEL = 4L

        fun newInstance(isRunning: Boolean, serverIp: String?): WebServerActionDialogFragment {
            return WebServerActionDialogFragment().apply {
                arguments = Bundle().apply {
                    putBoolean(ARG_IS_RUNNING, isRunning)
                    putString(ARG_SERVER_IP, serverIp)
                }
            }
        }

        fun show(fragmentManager: FragmentManager, fragment: WebServerActionDialogFragment) {
            GuidedStepSupportFragment.add(fragmentManager, fragment)
        }
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Status direkt von MainActivity holen (aktueller Status)
        val mainActivity = activity as? MainActivity
        isRunning = mainActivity?.isWebServerRunning() ?: false
        serverIp = if (isRunning) {
            mainActivity?.getWebServerUrl()?.let { url ->
                val regex = """http://([^:]+:\d+)""".toRegex()
                regex.find(url)?.groupValues?.getOrNull(1)
            }
        } else null
    }

    override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
        val title = "Web-Upload Server"
        val description = if (isRunning && serverIp != null) {
            "Server läuft auf http://$serverIp"
        } else {
            "Server ist gestoppt"
        }

        return GuidanceStylist.Guidance(
            title,
            description,
            "",
            ContextCompat.getDrawable(requireContext(), R.drawable.ic_web)
        )
    }

    override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
        // Status nochmal aktualisieren (falls sich was geändert hat)
        val mainActivity = activity as? MainActivity
        isRunning = mainActivity?.isWebServerRunning() ?: false

        if (isRunning) {
            actions.add(GuidedAction.Builder(requireContext())
                .id(ACTION_STOP)
                .title("Server stoppen")
                .description("Web-Upload beenden")
                .build())
        } else {
            actions.add(GuidedAction.Builder(requireContext())
                .id(ACTION_START)
                .title("Server starten")
                .description("Web-Upload aktivieren")
                .build())
        }

        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_SETTINGS)
            .title("Konfiguration")
            .description("Port und Passwort einstellen")
            .build())

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

    override fun onGuidedActionClicked(action: GuidedAction) {
        val mainActivity = activity as? MainActivity

        when (action.id) {
            ACTION_START -> {
                mainActivity?.startWebServer()
                parentFragmentManager.popBackStack()
            }
            ACTION_STOP -> {
                mainActivity?.stopWebServer()
                parentFragmentManager.popBackStack()
            }
            ACTION_SETTINGS -> {
                // Settings laden und dann zur Konfiguration wechseln
                viewLifecycleOwner.lifecycleScope.launch {
                    val settings = settingsRepository.getSettings()
                    GuidedStepSupportFragment.add(
                        parentFragmentManager,
                        WebServerSettingsFragment.newInstance(
                            port = settings.webServerPort,
                            passwordEnabled = settings.webServerPasswordEnabled,
                            password = settings.webServerPassword,
                            autoStart = settings.webServerAutoStart
                        )
                    )
                }
            }
            ACTION_CANCEL -> {
                parentFragmentManager.popBackStack()
            }
        }
    }
}

/**
 * Konfigurationsfragment für WebServer-Einstellungen
 */
class WebServerSettingsFragment : GuidedStepSupportFragment() {

    private lateinit var settingsRepository: SettingsRepository
    private var currentPort: Int = 8080
    private var passwordEnabled: Boolean = false
    private var currentPassword: String = ""
    private var autoStart: Boolean = false

    companion object {
        private const val ACTION_PORT = 1L
        private const val ACTION_PASSWORD_ENABLED = 2L
        private const val ACTION_PASSWORD = 3L
        private const val ACTION_AUTOSTART = 4L
        private const val ACTION_SAVE = 10L
        private const val ACTION_CANCEL = 11L

        private const val ARG_PORT = "arg_port"
        private const val ARG_PASSWORD_ENABLED = "arg_password_enabled"
        private const val ARG_PASSWORD = "arg_password"
        private const val ARG_AUTOSTART = "arg_autostart"

        fun newInstance(port: Int, passwordEnabled: Boolean, password: String, autoStart: Boolean): WebServerSettingsFragment {
            return WebServerSettingsFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_PORT, port)
                    putBoolean(ARG_PASSWORD_ENABLED, passwordEnabled)
                    putString(ARG_PASSWORD, password)
                    putBoolean(ARG_AUTOSTART, autoStart)
                }
            }
        }
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Werte aus Arguments laden (wurden vom aufrufenden Fragment gesetzt)
        arguments?.let { args ->
            currentPort = args.getInt(ARG_PORT, 8080)
            passwordEnabled = args.getBoolean(ARG_PASSWORD_ENABLED, false)
            currentPassword = args.getString(ARG_PASSWORD, "") ?: ""
            autoStart = args.getBoolean(ARG_AUTOSTART, false)
        }
    }

    override fun onStart() {
        super.onStart()
        // Werte bei jedem Start neu aus DB laden (falls Fragment wiederverwendet wird)
        viewLifecycleOwner.lifecycleScope.launch {
            val settings = settingsRepository.getSettings()
            currentPort = settings.webServerPort
            passwordEnabled = settings.webServerPasswordEnabled
            currentPassword = settings.webServerPassword
            autoStart = settings.webServerAutoStart

            // UI aktualisieren
            findActionById(ACTION_PORT)?.let { action ->
                action.description = currentPort.toString()
                notifyActionChanged(findActionPositionById(ACTION_PORT))
            }
            findActionById(ACTION_PASSWORD_ENABLED)?.let { action ->
                action.isChecked = passwordEnabled
                action.description = if (passwordEnabled) "Aktiviert" else "Deaktiviert"
                notifyActionChanged(findActionPositionById(ACTION_PASSWORD_ENABLED))
            }
            findActionById(ACTION_PASSWORD)?.let { action ->
                action.isEnabled = passwordEnabled
                action.description = if (passwordEnabled) {
                    if (currentPassword.isNotEmpty()) "••••••••" else ""
                } else {
                    "Deaktiviert"
                }
                action.editDescription = currentPassword
                notifyActionChanged(findActionPositionById(ACTION_PASSWORD))
            }
            findActionById(ACTION_AUTOSTART)?.let { action ->
                action.isChecked = autoStart
                action.description = if (autoStart) "Server startet beim Gerätestart" else "Deaktiviert"
                notifyActionChanged(findActionPositionById(ACTION_AUTOSTART))
            }
        }
    }

    override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
        return GuidanceStylist.Guidance(
            "WebServer Konfiguration",
            "Port und Passwortschutz einstellen",
            "",
            ContextCompat.getDrawable(requireContext(), R.drawable.ic_settings)
        )
    }

    override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
        // Port Eingabe
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_PORT)
            .title("Port")
            .description(currentPort.toString())
            .descriptionEditable(true)
            .descriptionEditInputType(android.text.InputType.TYPE_CLASS_NUMBER)
            .build())

        // Passwort aktivieren
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_PASSWORD_ENABLED)
            .title("Passwortschutz")
            .description(if (passwordEnabled) "Aktiviert" else "Deaktiviert")
            .checkSetId(GuidedAction.CHECKBOX_CHECK_SET_ID)
            .checked(passwordEnabled)
            .build())

        // Passwort Eingabe - editDescription enthält das echte Passwort,
        // description zeigt die maskierte Version
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_PASSWORD)
            .title("Passwort")
            .description(if (passwordEnabled) {
                if (currentPassword.isNotEmpty()) "••••••••" else ""
            } else {
                "Deaktiviert"
            })
            .editDescription(currentPassword)
            .descriptionEditable(true)
            .descriptionEditInputType(android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD)
            .enabled(passwordEnabled)
            .build())

        // Autostart beim Geräte-Boot
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_AUTOSTART)
            .title("Autostart beim Boot")
            .description(if (autoStart) "Server startet beim Gerätestart" else "Deaktiviert")
            .checkSetId(GuidedAction.CHECKBOX_CHECK_SET_ID)
            .checked(autoStart)
            .build())

        // Speichern
        actions.add(GuidedAction.Builder(requireContext())
            .id(ACTION_SAVE)
            .title("Speichern")
            .build())

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

    override fun onGuidedActionClicked(action: GuidedAction) {
        when (action.id) {
            ACTION_PASSWORD_ENABLED -> {
                passwordEnabled = action.isChecked
                // Passwort-Feld aktivieren/deaktivieren
                val passwordAction = findActionById(ACTION_PASSWORD)
                passwordAction?.isEnabled = passwordEnabled
                passwordAction?.description = if (passwordEnabled) {
                    if (currentPassword.isNotEmpty()) "••••••••" else ""
                } else {
                    "Deaktiviert"
                }
                notifyActionChanged(findActionPositionById(ACTION_PASSWORD))

                // Beschreibung der Checkbox aktualisieren
                action.description = if (passwordEnabled) "Aktiviert" else "Deaktiviert"
                notifyActionChanged(findActionPositionById(ACTION_PASSWORD_ENABLED))
            }
            ACTION_AUTOSTART -> {
                autoStart = action.isChecked
                action.description = if (autoStart) "Server startet beim Gerätestart" else "Deaktiviert"
                notifyActionChanged(findActionPositionById(ACTION_AUTOSTART))
            }
            ACTION_SAVE -> {
                saveSettings()
            }
            ACTION_CANCEL -> {
                parentFragmentManager.popBackStack()
            }
        }
    }

    override fun onGuidedActionEditedAndProceed(action: GuidedAction): Long {
        when (action.id) {
            ACTION_PORT -> {
                val portStr = action.description?.toString() ?: "8080"
                val port = portStr.toIntOrNull() ?: 8080
                currentPort = port.coerceIn(1, 65535)
                action.description = currentPort.toString()
                notifyActionChanged(findActionPositionById(ACTION_PORT))
            }
            ACTION_PASSWORD -> {
                // editDescription enthält das eingegebene Passwort
                currentPassword = action.editDescription?.toString() ?: ""
                // Maskierte Anzeige in der Vorschau, leerer String wenn kein Passwort
                action.description = if (currentPassword.isNotEmpty()) "••••••••" else ""
                // editDescription für nächste Bearbeitung aktualisieren
                action.editDescription = currentPassword
                notifyActionChanged(findActionPositionById(ACTION_PASSWORD))
            }
        }
        return GuidedAction.ACTION_ID_CURRENT
    }

    private fun saveSettings() {
        // Validierung
        if (passwordEnabled && currentPassword.isEmpty()) {
            Toast.makeText(context, "Passwort ist erforderlich wenn aktiviert", Toast.LENGTH_SHORT).show()
            return
        }

        val mainActivity = activity as? MainActivity

        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val currentSettings = settingsRepository.getSettings()
                settingsRepository.updateSettings(
                    currentSettings.copy(
                        webServerPort = currentPort,
                        webServerPasswordEnabled = passwordEnabled,
                        webServerPassword = currentPassword,
                        webServerAutoStart = autoStart
                    )
                )

                // WebServer neustarten wenn er läuft
                if (mainActivity?.isWebServerRunning() == true) {
                    mainActivity.stopWebServer()
                    mainActivity.startWebServer()
                    Toast.makeText(context, "Einstellungen gespeichert, Server neugestartet", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "Einstellungen gespeichert", Toast.LENGTH_SHORT).show()
                }

                // Zurück zum vorherigen Screen
                parentFragmentManager.popBackStack()
            } catch (e: Exception) {
                Toast.makeText(context, "Fehler beim Speichern: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
