package com.omixlab.lckcontrol.ui.accounts

import android.app.Activity
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.omixlab.lckcontrol.data.repository.AccountRepository
import com.omixlab.lckcontrol.shared.LinkedAccount
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

data class AvailableProvider(
    val serviceId: String,
    val displayName: String,
)

val ALL_PROVIDERS = listOf(
    AvailableProvider("YOUTUBE", "YouTube"),
    AvailableProvider("TWITCH", "Twitch"),
)

@HiltViewModel
class AccountsViewModel @Inject constructor(
    private val accountRepository: AccountRepository,
) : ViewModel() {

    val accounts: StateFlow<List<LinkedAccount>> = accountRepository.observeAccounts()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    private val _linkError = MutableStateFlow<String?>(null)
    val linkError: StateFlow<String?> = _linkError.asStateFlow()

    // Custom RTMP dialog state
    private val _showCustomRtmpDialog = MutableStateFlow(false)
    val showCustomRtmpDialog: StateFlow<Boolean> = _showCustomRtmpDialog.asStateFlow()

    private val _customRtmpName = MutableStateFlow("")
    val customRtmpName: StateFlow<String> = _customRtmpName.asStateFlow()

    private val _customRtmpUrl = MutableStateFlow("")
    val customRtmpUrl: StateFlow<String> = _customRtmpUrl.asStateFlow()

    private val _customRtmpKey = MutableStateFlow("")
    val customRtmpKey: StateFlow<String> = _customRtmpKey.asStateFlow()

    private val _isCreatingCustomRtmp = MutableStateFlow(false)
    val isCreatingCustomRtmp: StateFlow<Boolean> = _isCreatingCustomRtmp.asStateFlow()

    init {
        // Sync accounts from backend on load
        viewModelScope.launch {
            try {
                accountRepository.syncAccounts()
            } catch (e: Exception) {
                // Offline — local cache still works
            }
        }
    }

    fun linkAccount(activity: Activity, serviceId: String) {
        viewModelScope.launch {
            _linkError.value = null
            try {
                val url = when (serviceId) {
                    "YOUTUBE" -> accountRepository.getYouTubeAuthUrl()
                    "TWITCH" -> accountRepository.getTwitchAuthUrl()
                    else -> throw IllegalArgumentException("Unknown service: $serviceId")
                }
                val customTabsIntent = CustomTabsIntent.Builder().build()
                customTabsIntent.launchUrl(activity, Uri.parse(url))
            } catch (e: Exception) {
                _linkError.value = e.message ?: "Failed to start auth flow"
            }
        }
    }

    fun toggleAccountEnabled(accountId: String, enabled: Boolean) {
        viewModelScope.launch {
            try {
                accountRepository.setAccountEnabled(accountId, enabled)
            } catch (e: Exception) {
                _linkError.value = e.message ?: "Failed to update account"
            }
        }
    }

    fun unlinkAccount(accountId: String) {
        viewModelScope.launch {
            try {
                accountRepository.unlinkAccount(accountId)
            } catch (e: Exception) {
                _linkError.value = e.message ?: "Failed to unlink account"
            }
        }
    }

    fun showCustomRtmpDialog() {
        _customRtmpName.value = ""
        _customRtmpUrl.value = ""
        _customRtmpKey.value = ""
        _showCustomRtmpDialog.value = true
    }

    fun dismissCustomRtmpDialog() {
        _showCustomRtmpDialog.value = false
    }

    fun setCustomRtmpName(name: String) { _customRtmpName.value = name }
    fun setCustomRtmpUrl(url: String) { _customRtmpUrl.value = url }
    fun setCustomRtmpKey(key: String) { _customRtmpKey.value = key }

    fun createCustomRtmpAccount() {
        val name = _customRtmpName.value.trim()
        val url = _customRtmpUrl.value.trim()
        val key = _customRtmpKey.value.trim()
        if (name.isBlank() || url.isBlank() || key.isBlank()) {
            _linkError.value = "All fields are required"
            return
        }
        viewModelScope.launch {
            _isCreatingCustomRtmp.value = true
            try {
                accountRepository.createCustomRtmpAccount(name, url, key)
                _showCustomRtmpDialog.value = false
            } catch (e: Exception) {
                _linkError.value = e.message ?: "Failed to create custom RTMP account"
            } finally {
                _isCreatingCustomRtmp.value = false
            }
        }
    }

    fun clearError() {
        _linkError.value = null
    }
}
