package com.vpn.fastestvpnservice.screens

import android.content.res.Configuration
import android.util.Log
import androidx.compose.animation.Animatable
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.LocalOverscrollConfiguration
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.SearchBar
import androidx.compose.material3.SearchBarDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.lifecycle.viewmodel.compose.viewModel
import com.vpn.fastestvpnservice.R
import com.vpn.fastestvpnservice.customItems.CountryItem
import com.vpn.fastestvpnservice.customItems.ServerItem
import com.vpn.fastestvpnservice.customItems.ServerSearchItem
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.AddTextSettings
import com.vpn.fastestvpnservice.sealedClass.Screen
import com.vpn.fastestvpnservice.viewmodels.SearchListViewModel
import com.vpn.fastestvpnservice.viewmodels.ServerListViewModel
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ServerList(
    navHostController: NavHostController,
    isAllLocationsShown: Boolean,
) {
    val focusManager = LocalFocusManager.current
    val context = LocalContext.current

    var serverListViewModel: ServerListViewModel = viewModel {
        ServerListViewModel(context = context)
    }
    val basePreferenceHelper = BasePreferenceHelper(context)

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                color = MaterialTheme.colorScheme.background
            )

    ) {
        HeaderRowSL(navHostController = navHostController)
        Column(
            modifier = Modifier
                .padding(horizontal = 16.dp)
                .padding(top = 100.dp)
        ) {
            ShowSearchBar(serverListViewModel, basePreferenceHelper)

            val serverTabItems = listOf("Recommended", "All Locations")
            val pagerState = rememberPagerState(pageCount = {serverTabItems.size})
            val selectedIndex by remember { derivedStateOf { pagerState.currentPage } }
            val scope = rememberCoroutineScope()

            if (Screen.ServerList.isTrue) {
                LaunchedEffect(key1 = true) {
                    scope.launch {
                        pagerState.animateScrollToPage(1)
                    }
                }
            }

            // Tab Row [Recommended, All Locations]
            TabRow(
                selectedTabIndex = selectedIndex,
                containerColor = Color.White,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
                    .background(Color.Transparent)
                    .clip(RoundedCornerShape(28.dp))
                    .height(68.dp)
                   ,
                indicator = {
//                    TabRowDefaults.Indicator()
                },
                divider = {}
            ) {
                serverTabItems.forEachIndexed { index, currentTab ->

                    val color = remember { Animatable(Color.White) }

                    LaunchedEffect(key1 = selectedIndex == index) {
                        color.animateTo(
                            if (selectedIndex == index) Color(0xFFE9EDF9)
                            else Color.White
                        )
                    }

                    Tab(
                        selected = selectedIndex == index,
                        onClick = {
                            scope.launch {
                                pagerState.animateScrollToPage(index)
                            }
                        },
                        selectedContentColor = Color.White,
                        unselectedContentColor = Color.White,
                        text = { Text(text = currentTab,
                            style = TextStyle(
                                color = colorResource(id = R.color.dark_blue_gray_text),
                                fontSize = 14.sp,
                                textAlign = TextAlign.Center
                            )
                            ) },
                        modifier = Modifier
                            .padding(
                                start = 10.dp, end = 10.dp,
                                top = 10.dp, bottom = 10.dp
                            )
                            .background(
                                color = color.value,
                                shape = RoundedCornerShape(20.dp)
                            )

                    )
                }
            }

                HorizontalPager(
                    state = pagerState,
                    modifier = Modifier
                        .padding(top = 14.dp)
                        .fillMaxWidth()
                        .background(Color.Transparent),
                    userScrollEnabled = false
                ) { page ->
                    CompositionLocalProvider(
                        LocalOverscrollConfiguration provides null
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(top = 0.dp, bottom = 10.dp)
                        ) {
                            if (page == 0) {
                                ShowRecommendedList(serverListViewModel, basePreferenceHelper)
                            }
                            else if (page == 1) {
                                ShowAllLocationsList(serverListViewModel, basePreferenceHelper)
                            }
                        }
                    }

                }
        }
    }
}

@Composable
fun BoxScope.HeaderRowSL(
    navHostController: NavHostController) {
    IconButton(
        onClick = {
            navHostController.popBackStack()
//                    navHostController.navigate(BottomBarScreen.Help.route)
        },
        modifier = Modifier
            .align(Alignment.TopStart)
            .padding(top = 55.dp)
            .padding(start = 16.dp)
            .size(30.dp, 32.dp)
    ) {
        Icon(
            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
            contentDescription = "Arrow-Back",
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(30.dp, 32.dp)
        )
    }
    Surface(
        modifier = Modifier
            .padding(top = 55.dp)
            .height(32.dp)
            .align(Alignment.TopCenter)
            .padding(5.dp),
        color = colorResource(id = R.color.transparent)
    ) {
        Text(text = "Select Location",
            style = TextStyle(
                fontSize = 18.sp,
                color = MaterialTheme.colorScheme.primary,
                textAlign = TextAlign.Center,
                fontWeight = FontWeight.Medium
            ),
            modifier = Modifier.fillMaxHeight()

        )
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ColumnScope.ShowRecommendedList(
    serverListViewModel: ServerListViewModel,
    basePreferenceHelper: BasePreferenceHelper
) {
    CompositionLocalProvider(
        LocalOverscrollConfiguration provides null
    ) {
        LazyColumn(
            modifier = Modifier
                .padding(top = 14.dp),
        ) {
            /* Fav List */
            item{
                Row(
                    verticalAlignment = Alignment.Top,
                    horizontalArrangement = Arrangement.Start,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 10.dp, bottom = 10.dp)
                        .background(Color.Transparent)
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.unfav_server3x),
                        contentDescription = "Server Logo",
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier
                            .padding(bottom = 0.dp)
                            .size(19.dp)
                    )
                    Text(text = "Favorite Location",
                        style = TextStyle(
                            fontSize = 16.sp,
                            color = MaterialTheme.colorScheme.primary
                        ),
                        modifier = Modifier
                            .padding(start = 16.dp, bottom = 0.dp)
                            .align(Alignment.CenterVertically)
                    )
                }
            }
                val fav = basePreferenceHelper.getServerData()
                val filterData1 = fav.get(2).servers?.let {
                    serverListViewModel.filterServersByStreamingServers(
                        it
                    )
                }

            items(items = filterData1!!) { server ->
                ServerItem(server)
            }

            /* Smart List */
            item {
                Row(
                    verticalAlignment = Alignment.Top,
                    horizontalArrangement = Arrangement.Start,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 24.dp, bottom = 10.dp)
                        .background(Color.Transparent)
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.smartlogo3x),
                        contentDescription = "Server Logo",
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier
                            .padding(bottom = 0.dp)
                            .size(19.dp)
                    )
                    Text(text = "Smart Location",
                        style = TextStyle(
                            fontSize = 16.sp,
                            color = MaterialTheme.colorScheme.primary
                        ),
                        modifier = Modifier
                            .padding(start = 16.dp, bottom = 0.dp)
                            .align(Alignment.CenterVertically)
                    )
                }
            }

            val smart = basePreferenceHelper.getServerData()
            val filterData2 = smart.get(1).servers?.let {
                serverListViewModel.filterServersByStreamingServers(
                    it
                )
            }

            items(items = filterData2!!) { server ->
                ServerItem(server)
            }

            /* Recent List */
            item {
                Row(
                    verticalAlignment = Alignment.Top,
                    horizontalArrangement = Arrangement.Start,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 24.dp, bottom = 10.dp)
                        .background(Color.Transparent)
                ) {
                    Icon(
                        painter = painterResource(
                            id = R.drawable.recent3x),
                        contentDescription = "Server Logo",
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier
                            .padding(bottom = 0.dp)
                            .size(19.dp)
                    )
                    Text(text = "Recent Location",
                        style = TextStyle(
                            fontSize = 16.sp,
                            color = MaterialTheme.colorScheme.primary
                        ),
                        modifier = Modifier
                            .padding(start = 16.dp, bottom = 0.dp)
                            .align(Alignment.CenterVertically)
                    )
                }
            }
            val recent = basePreferenceHelper.getServerData()
            val filterData3 = recent.get(1).servers?.let {
                serverListViewModel.filterServersByStreamingServers(
                    it
                )
            }

            items(items = filterData3!!) { server ->
                ServerItem(server)
            }

            /* Recommended List */
            item {
                Row(
                    verticalAlignment = Alignment.Top,
                    horizontalArrangement = Arrangement.Start,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 24.dp, bottom = 10.dp)
                        .background(Color.Transparent)
                ) {
                    Icon(
                        painter = painterResource(
                            id = R.drawable.recommended3x),
                        contentDescription = "Server Logo",
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier
                            .padding(bottom = 0.dp)
                            .size(19.dp)
                    )
                    Text(text = "Recommended Location",
                        style = TextStyle(
                            fontSize = 16.sp,
                            color = MaterialTheme.colorScheme.primary
                        ),
                        modifier = Modifier
                            .padding(start = 16.dp, bottom = 0.dp)
                            .align(Alignment.CenterVertically)
                    )
                }
            }

            val recommend = basePreferenceHelper.getServerData()
            val filterData4 = recommend.get(1).servers?.let {
                serverListViewModel.filterServersByStreamingServers(
                    it
                )
            }

            items(items = filterData4!!) { server ->
                ServerItem(server)
            }
        }
    }

}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ColumnScope.ShowAllLocationsList(
    serverListViewModel: ServerListViewModel,
    basePreferenceHelper: BasePreferenceHelper
) {
    val allLocationsTabItems = listOf(
        "Countries", "Streaming", "D-VPN", "P2P"
    )
    val serverData = basePreferenceHelper.getServerData()
    val filterData = serverData.get(0).servers?.let {
        serverListViewModel.filterServersByISO(
            it
        )
    }

    val pagerState = rememberPagerState(pageCount = { serverData.size })
    val selectedIndex by remember { derivedStateOf { pagerState.currentPage } }
    val scope = rememberCoroutineScope()



    serverData.forEachIndexed { index, server ->
        Log.d("test_data", "${server.name} ${server.servers?.size} -> ${serverData.size}")
    }

    androidx.compose.material3.ScrollableTabRow(
        selectedTabIndex = selectedIndex,
        containerColor = Color.Transparent,
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 0.dp)
            .background(Color.Transparent)
            .clip(RoundedCornerShape(0.dp))
            .height(68.dp),
        edgePadding = 0.dp,
        indicator = { selectedTab ->
            TabRowDefaults.Indicator(
                modifier = Modifier.tabIndicatorOffset(selectedTab[selectedIndex]),
                color = colorResource(id = R.color.blue_text)
            )
        },
//                                divider = {}
    ) {
        serverData.forEachIndexed { index1, locationTab ->
//                                    val color = remember { Animatable(Color.Transparent) }
            var color by remember { mutableStateOf(Color.Transparent) }
            var alpha by remember { mutableFloatStateOf(1F) }

                color =
                    if (selectedIndex == index1)
                        Color(0xFF2952c3)
                    else MaterialTheme.colorScheme.primary
                alpha = if (selectedIndex == index1)
                    1F else 0.5F

            Tab(
                selected = selectedIndex == index1,
                onClick = {
                    scope.launch {
                        pagerState.animateScrollToPage(index1)
                    }
                },
                selectedContentColor = Color.White,
                unselectedContentColor = Color.White,
                text = {
                    Text(
                        text = locationTab.name!!,
                        style = TextStyle(
                            color = color,
                            fontSize = 14.sp,
                            textAlign = TextAlign.Center,
                        ),
                        modifier = Modifier
                            .fillMaxWidth()
                            .alpha(alpha)
                    )
                },
                modifier = Modifier

                    .background(
//                        color = color.value,
                        color = Color.Transparent,
                        shape = RoundedCornerShape(0.dp)
                    )
            )
        }
    }

    val data = basePreferenceHelper.getServerData()


    var isServersListExpanded by rememberSaveable { mutableStateOf(List(data.size) {true}) }
    var isStreamingExpanded by rememberSaveable { mutableStateOf(true) }
    var isDvpnExpanded by rememberSaveable { mutableStateOf(true) }
    var isP2PExpanded by rememberSaveable { mutableStateOf(true) }

    val isServersTabExpanded by rememberSaveable { mutableStateOf(listOf(true)) }

//    val rotationState by animateFloatAsState(
//        targetValue = if (isCountriesExpanded) 180f else 0f,
//        label = if (isCountriesExpanded) "Show Less" else "Show More"
//    )

    HorizontalPager(
        state = pagerState,
        modifier = Modifier
            .padding(top = 16.dp)
            .fillMaxWidth()
            .background(Color.Transparent),
        userScrollEnabled = false
    ) { serverTabPager ->
        CompositionLocalProvider(
            LocalOverscrollConfiguration provides null
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                var serverTitle by rememberSaveable { mutableStateOf("") }
                var icon by rememberSaveable { mutableStateOf(0) }

//                when (serverTabPager) {
//                    0 -> {
//                        serverTitle = serverData[0].name!!
//                        icon = if (isCountriesExpanded) R.drawable.dragarrow3x
//                        else R.drawable.downarrow3x
//                    }
//                    1 -> {
//                        serverTitle = serverData[1].name!!
//                        icon = if (isStreamingExpanded) R.drawable.dragarrow3x
//                        else R.drawable.downarrow3x
//                    }
//                    2 -> {
//                        serverTitle = serverData[2].name!!
//                        icon = if (isDvpnExpanded) R.drawable.dragarrow3x
//                        else R.drawable.downarrow3x
//                    }
//                    3 -> {
//                        serverTitle = serverData[3].name!!
//                        icon = if (isP2PExpanded) R.drawable.dragarrow3x
//                        else R.drawable.downarrow3x
//                    }
//                    4 -> {
//                        serverTitle = serverData[4].name!!
//                        icon = if (isP2PExpanded) R.drawable.dragarrow3x
//                        else R.drawable.downarrow3x
//                    }
//                }

                serverTitle = serverData[serverTabPager].name!!
                icon = if (isServersListExpanded[serverTabPager]) R.drawable.dragarrow3x
                else R.drawable.downarrow3x

                ShowHeaderItem(serverTitle, icon, serverTabPager) {
                    isServersListExpanded = isServersListExpanded.toMutableList().also {
                        it[serverTabPager] = !isServersListExpanded[serverTabPager]
                    }

                    //                    when (serverTabPager) {
//                        0 -> {
//                            isCountriesExpanded = !isCountriesExpanded
//                        }
//                        1 -> {
//                            isStreamingExpanded = !isStreamingExpanded
//                        }
//                        2 -> {
//                            isDvpnExpanded = !isDvpnExpanded
//                        }
//                        3 -> {
//                            isP2PExpanded = !isP2PExpanded
//                        }
//                    }
                }

                if (isServersListExpanded[serverTabPager]) {
                    CompositionLocalProvider(
                        LocalOverscrollConfiguration provides null
                    ) {
                        val filterServersData = if (data[serverTabPager].name?.lowercase().toString() == "servers") {
                            data.get(serverTabPager).servers?.let {
                                serverListViewModel.filterServersByISO(
                                    it
                                )
                            }
                        }
                        else {
                            data.get(serverTabPager).servers?.let {
                                serverListViewModel.filterServersByStreamingServers(
                                    it
                                )
                            }
                        }

                        Log.d("streaming_servers",data[serverTabPager].name?.toString() + filterServersData?.size.toString())


                        LazyColumn() {
                            items(items = filterServersData!!) { country ->
                                CountryItem(server = country, data[serverTabPager].name!!)
                            }
                        }
                    }
                }

//                when (serverTabPager) {
//                    0 -> {
//                        if (isCountriesExpanded) {
//                            CompositionLocalProvider(
//                                LocalOverscrollConfiguration provides null
//                            ) {
//                                val country = basePreferenceHelper.getServerData()
//                                val filterData = country.get(0).servers?.let {
//                                    serverListViewModel.filterServersByISO(
//                                        it
//                                    )
//                                }
//
//                                LazyColumn() {
//                                    items(items = filterData!!) { country ->
//                                        CountryItem(server = country)
//                                    }
//                                }
//                            }
//
//                        }
//                    }
//                    1 -> {
//                        if (isStreamingExpanded) {
//                            CompositionLocalProvider(
//                                LocalOverscrollConfiguration provides null
//                            ) {
//                                val streaming = basePreferenceHelper.getServerData()
//                                val filterData = streaming.get(1).servers?.let {
//                                    serverListViewModel.filterServersByStreamingServers(
//                                        it
//                                    )
//                                }
//                                LazyColumn() {
//                                    items(items = filterData!!) { streaming ->
//                                        ServerItem(server = streaming)
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    2 -> {
//                        if (isDvpnExpanded) {
//                            CompositionLocalProvider(
//                                LocalOverscrollConfiguration provides null
//                            ) {
//                                val dvpn = basePreferenceHelper.getServerData()
//                                val filterData = dvpn.get(2).servers?.let {
//                                    serverListViewModel.filterServersByISO(
//                                        it
//                                    )
//                                }
//
//                                LazyColumn() {
//                                    items(items = filterData!!) { dvpn ->
//                                        ServerItem(server = dvpn)
//                                    }
//                                }
//                            }
//
//                        }
//                    }
//                    3 -> {
//                        if (isP2PExpanded) {
//                            CompositionLocalProvider(
//                                LocalOverscrollConfiguration provides null
//                            ) {
//                                val p2p = basePreferenceHelper.getServerData()
//                                val filterData = p2p.get(3).servers?.let {
//                                    serverListViewModel.filterServersByISO(
//                                        it
//                                    )
//                                }
//
//                                LazyColumn() {
//                                    items(items = filterData!!) { p2p ->
//                                        ServerItem(server = p2p)
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
            }
        }

    }
}

@Composable
fun ColumnScope.ShowHeaderItem(
    serverTitle: String,
    icon: Int,
    serverTabPager: Int,
    onClick: () -> Unit
) {
    Row(
        verticalAlignment = Alignment.Top,
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 10.dp, bottom = 10.dp)
            .background(Color.Transparent)
    ) {
        Text(
            text = serverTitle,
            style = TextStyle(
                fontSize = 16.sp,
                color = MaterialTheme.colorScheme.primary
            ),
            modifier = Modifier
                .padding(start = 0.dp, bottom = 0.dp)
                .align(Alignment.CenterVertically)
        )
        Icon(
            painter = painterResource(id = icon),
            contentDescription = "Server Logo",
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier
                .padding(bottom = 0.dp, end = 12.dp)
                .size(12.dp, 7.dp)
                .align(Alignment.CenterVertically)
//                        .rotate(rotationState)
//                        .rotate(rotationState2)
//                        .rotate(rotationState3)
//                        .rotate(rotationState4)
                .pointerInput(Unit) {
                    detectTapGestures {
                        onClick()
//                        when (serverTabPager) {
////                            0 -> {
////                                onClick()
////                            }
////
////                            1 -> {
////                                onClick()
////                            }
////
////                            2 -> {
////                                onClick()
////                            }
////
////                            3 -> {
////                                onClick()
////                            }
//                        }
                    }
                }
        )
    }

    Surface(
        modifier = Modifier
            .padding(top = 11.dp, end = 0.dp)
            .height(1.dp)
            .fillMaxWidth()
            .alpha(0.6F)
        ,
        color = colorResource(id = R.color.gray_icon)
    ) {}
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ColumnScope.ShowSearchBar(
    serverListViewModel: ServerListViewModel,
    basePreferenceHelper: BasePreferenceHelper) {

    val context = LocalContext.current
    val searchListViewModel: SearchListViewModel = viewModel{
        SearchListViewModel(context, serverListViewModel)
    }

//    var searchText by remember { mutableStateOf("") }
//    var isActive by remember { mutableStateOf(false) }

    val searchText = searchListViewModel.searchText.observeAsState().value
    val isActive = searchListViewModel.isActive.observeAsState().value

    var isFilter by remember { mutableStateOf(false) }
    val sheetState = rememberModalBottomSheetState()
    val filterList = listOf("Popularity", "Alphabetically")
    var selectedFilterList by remember { mutableStateOf(filterList[0]) }

    SearchBar(
        query = searchText!!,
        onQueryChange = {
            searchListViewModel.searchTextChange(it)
        },
        onSearch = {
            searchListViewModel.isActiveChange(false)
        },
        active = isActive!!,
        onActiveChange = {
            searchListViewModel.isActiveChange(it)
        },
        placeholder = {
            Text(
                text = "Search Location",
                style = TextStyle(
                    fontSize = 14.sp,
                    color = colorResource(id = R.color.dark_blue_gray_text)
                ),
                modifier = Modifier

            )
        },
        leadingIcon = {
            Icon(
                painter = painterResource(id = R.drawable.search3x),
                contentDescription = "Search Icon",

                modifier = Modifier
                    .size(21.dp)
            )
        },
        trailingIcon = {
            IconButton(onClick = { isFilter = true }) {
                Icon(
                    painter = painterResource(id = R.drawable.filter3x),
                    contentDescription = "Search Icon",
                    tint = colorResource(id = R.color.dark_blue_gray_text),
                    modifier = Modifier
                        .size(24.dp)
                )
            }
        },
        colors = SearchBarDefaults.colors(
            containerColor = colorResource(id = R.color.white),
            dividerColor = Color.Transparent,
            inputFieldColors = TextFieldDefaults.colors(
                focusedTextColor = colorResource(id = R.color.dark_blue_gray_text),
                unfocusedTextColor = colorResource(id = R.color.dark_blue_gray_text),
                unfocusedIndicatorColor = colorResource(id = R.color.dark_blue_gray_text),
                focusedIndicatorColor = colorResource(id = R.color.dark_blue_gray_text),
                disabledIndicatorColor = colorResource(id = R.color.dark_blue_gray_text),
                cursorColor = colorResource(id = R.color.dark_blue_gray_text),
            )
        ),
        modifier = Modifier
            .fillMaxWidth()
    ) {
        CompositionLocalProvider(
            LocalOverscrollConfiguration provides null
        ) {
            LazyColumn(
                modifier = Modifier
                    .padding(top = 0.dp, bottom = 0.dp),
            ) {
                val searchServersList = searchListViewModel.countriesList.value
                items(items = searchServersList!!) { server ->
                    ServerSearchItem(server)
                }
            }
        }
    }

    if (isFilter) {
        ModalBottomSheet(
            onDismissRequest = { isFilter = false },
            sheetState = sheetState,
            containerColor = MaterialTheme.colorScheme.background
        ) {
            Box(modifier = Modifier
                .background(Color.Transparent)
                .fillMaxWidth()
                .height(215.dp)
                .padding(start = 0.dp, top = 10.dp),
            ) {
                Column(
                    verticalArrangement = Arrangement.Top,
                    horizontalAlignment = Alignment.Start
                ) {
                    AddTextSettings(
                        text = "Sort By",
                        size = 18.sp,
                        color = MaterialTheme.colorScheme.primary,
                        bottomPadding = 20.dp,
                        startPadding = 16.dp
                    )
                    filterList.forEach { filter ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .background(Color.Transparent)
                                .padding(start = 2.dp)
//                                    .selectable(
//                                        selected = selectedProtocol == protocol,
//                                        onClick = {
//                                            selectedProtocol = protocol
//                                        },
//                                    )
//                                    .indication(
//                                        indication = null,
//                                        interactionSource = remember {
//                                            MutableInteractionSource()
//                                        }
//                                    )
                            ,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            RadioButton(
                                selected = filter == selectedFilterList,
                                onClick = {
                                    selectedFilterList = filter

                                },
                                colors = RadioButtonDefaults.colors(
                                    selectedColor = colorResource(id = R.color.radio_button_blue),
                                    unselectedColor = colorResource(id = R.color.gray_icon)),
                            )
                            Text(text = filter,
                                modifier = Modifier.padding(start = 12.dp),
                                style = TextStyle(
                                    fontSize = 14.sp,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            )
                        }
                    }
                }
            }
        }
    }
}

@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun ServerListPreview() {
    ServerList(rememberNavController(), false)
}