package com.example.livingai.pages.listings

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.livingai.R
import com.example.livingai.domain.model.AnimalProfile
import com.example.livingai.pages.commons.Dimentions
import com.example.livingai.pages.components.AnimalProfileCard
import com.example.livingai.pages.components.CommonScaffold
import com.example.livingai.pages.components.LabeledDropdown
import com.example.livingai.pages.navigation.Route
import kotlinx.coroutines.flow.collectLatest
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListingsScreen(
    navController: NavController,
    viewModel: ListingsViewModel = koinViewModel()
) {
    val animalProfiles: LazyPagingItems<AnimalProfile> = viewModel.animalProfiles.collectAsLazyPagingItems()
    val searchQuery by viewModel.searchQuery.collectAsState()
    val selectedSpecies by viewModel.selectedSpecies.collectAsState()
    val selectedBreed by viewModel.selectedBreed.collectAsState()
    val minAge by viewModel.minAge.collectAsState()
    val maxAge by viewModel.maxAge.collectAsState()

    val speciesList = stringArrayResource(id = R.array.species_list).toList()
    val breedList = stringArrayResource(id = R.array.cow_breed_list).toList()

    // Listen for events from the ViewModel to refresh the list
    LaunchedEffect(Unit) {
        viewModel.events.collectLatest { event ->
            when (event) {
                is ListingsEvent.Refresh -> {
                    animalProfiles.refresh()
                }
            }
        }
    }

    // Listen for results from the AddProfileScreen
    val savedStateHandle = navController.currentBackStackEntry?.savedStateHandle
    LaunchedEffect(savedStateHandle) {
        if (savedStateHandle?.get<Boolean>("refresh_listings") == true) {
            animalProfiles.refresh()
            savedStateHandle.remove<Boolean>("refresh_listings")
        }
    }

    CommonScaffold(
        navController = navController,
        title = stringResource(R.string.top_bar_listings),
        showFab = true,
        onFabClick = { navController.navigate(Route.AddProfileScreen()) }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .padding(Dimentions.SMALL_PADDING_TEXT)
        ) {
            // Search Bar
            OutlinedTextField(
                value = searchQuery,
                onValueChange = { viewModel.searchQuery.value = it },
                label = { Text("Search") },
                leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = Dimentions.SMALL_PADDING_TEXT),
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                singleLine = true
            )

            // Filters
            Column(
                verticalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_INPUT),
                modifier = Modifier.padding(bottom = Dimentions.MEDIUM_PADDING)
            ) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_INPUT),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    // Species Filter
                    LabeledDropdown(
                        labelRes = R.string.label_species,
                        options = listOf("All") + speciesList,
                        selected = selectedSpecies ?: "All",
                        onSelected = { 
                            viewModel.selectedSpecies.value = if (it == "All") null else it 
                        },
                        modifier = Modifier.weight(1f)
                    )

                    // Breed Filter
                    LabeledDropdown(
                        labelRes = R.string.label_breed,
                        options = listOf("All") + breedList,
                        selected = selectedBreed ?: "All",
                        onSelected = { 
                            viewModel.selectedBreed.value = if (it == "All") null else it 
                        },
                        modifier = Modifier.weight(1f)
                    )
                }

                Row(
                    horizontalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_INPUT),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    OutlinedTextField(
                        value = minAge,
                        onValueChange = { viewModel.minAge.value = it },
                        label = { Text("Min Age") },
                        modifier = Modifier.weight(1f),
                        keyboardOptions = KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number)
                    )
                    OutlinedTextField(
                        value = maxAge,
                        onValueChange = { viewModel.maxAge.value = it },
                        label = { Text("Max Age") },
                        modifier = Modifier.weight(1f),
                        keyboardOptions = KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number)
                    )
                }
            }

            // Handle loading and empty states
            when (animalProfiles.loadState.refresh) {
                is LoadState.Loading -> {
                    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                        CircularProgressIndicator()
                    }
                }
                is LoadState.NotLoading -> {
                    if (animalProfiles.itemCount == 0) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Icon(Icons.Default.Search, contentDescription = null, modifier = Modifier.size(64.dp), tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f))
                                Text(text = "No results found", style = MaterialTheme.typography.bodyLarge)
                            }
                        }
                    } else {
                        LazyColumn(
                            contentPadding = PaddingValues(bottom = Dimentions.SMALL_PADDING_TEXT),
                            verticalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_TEXT)
                        ) {
                            items(count = animalProfiles.itemCount) { index ->
                                val item = animalProfiles[index]
                                item?.let { profile ->
                                    AnimalProfileCard(
                                        animalProfile = profile,
                                        onEdit = { 
                                             navController.navigate(Route.AddProfileScreen(animalId = profile.animalId, loadEntry = true))
                                        },
                                        onRate = { navController.navigate(Route.RatingScreen(animalId = profile.animalId)) },
                                        onDelete = { viewModel.deleteAnimalProfile(profile.animalId) }
                                    )
                                }
                            }
                        }
                    }
                }
                is LoadState.Error -> {
                     Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(text = "Error loading data", color = MaterialTheme.colorScheme.error)
                    }
                }
            }
        }
    }
}
