package com.example.livingai.pages.addprofile

import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.navigation.NavController
import com.example.livingai.R
import com.example.livingai.pages.commons.Dimentions
import com.example.livingai.pages.components.CommonScaffold
import com.example.livingai.pages.components.ImageThumbnailButton
import com.example.livingai.pages.components.LabeledDropdown
import com.example.livingai.pages.components.LabeledTextField
import com.example.livingai.pages.components.RadioGroup
import com.example.livingai.pages.components.VideoThumbnailButton
import com.example.livingai.utils.Constants

@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun AddProfileScreen(
    navController: NavController,
    viewModel: AddProfileViewModel,
    onSave: () -> Unit,
    onCancel: () -> Unit,
    onTakePhoto: (String) -> Unit,
    onTakeVideo: () -> Unit
) {
    val context = LocalContext.current

    // If opened for edit, attempt to load existing animal details
    LaunchedEffect(Unit) {
        val existing = viewModel.savedStateHandle?.get<String>("animalId")
        if (existing != null) viewModel.loadAnimal(existing)
    }
    
    val speciesList = stringArrayResource(id = R.array.species_list).toList()
    val breedList = stringArrayResource(id = R.array.cow_breed_list).toList()

    val reproList = listOf(
        stringResource(R.string.option_pregnant),
        stringResource(R.string.option_calved),
        stringResource(R.string.option_none)
    )

    val silhouette = Constants.silhouetteList.associateWith { item ->
        val resId = context.resources.getIdentifier("label_${item}", "string", context.packageName)
        if (resId != 0) resId else R.string.default_orientation_label
    }
    
    // Use ViewModel state
    var species by viewModel.species
    var breed by viewModel.breed
    var age by viewModel.age
    var milkYield by viewModel.milkYield
    var calvingNumber by viewModel.calvingNumber
    var reproductiveStatus by viewModel.reproductiveStatus
    var description by viewModel.description
    
    // Errors
    val speciesError by viewModel.speciesError
    val breedError by viewModel.breedError
    val ageError by viewModel.ageError
    val milkYieldError by viewModel.milkYieldError
    val calvingNumberError by viewModel.calvingNumberError
    val reproductiveStatusError by viewModel.reproductiveStatusError

    val photos = viewModel.photos
    val videoUri by viewModel.videoUri
    
    // Focus Requesters
    val speciesFocus = remember { FocusRequester() }
    val breedFocus = remember { FocusRequester() }
    val ageFocus = remember { FocusRequester() }
    val milkYieldFocus = remember { FocusRequester() }
    val calvingNumberFocus = remember { FocusRequester() }
    val reproductiveStatusFocus = remember { FocusRequester() } // Probably not useful for RadioGroup but good for consistency

    // Auto-focus logic on error
    LaunchedEffect(speciesError, breedError, ageError, milkYieldError, calvingNumberError, reproductiveStatusError) {
        if (speciesError != null) {
            speciesFocus.requestFocus()
        } else if (breedError != null) {
            breedFocus.requestFocus()
        } else if (ageError != null) {
            ageFocus.requestFocus()
        } else if (milkYieldError != null) {
            milkYieldFocus.requestFocus()
        } else if (calvingNumberError != null) {
            calvingNumberFocus.requestFocus()
        }
    }

    CommonScaffold(
        navController = navController,
        title = stringResource(id = R.string.top_bar_add_profile)
    ) { innerPadding ->
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            verticalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_INPUT),
            horizontalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_IMAGE),
            modifier = Modifier
                .padding(innerPadding)
                .padding(Dimentions.SMALL_PADDING_TEXT)
        ) {
            item(span = { GridItemSpan(2) }) {
                Column(
                    verticalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_INPUT)
                ) {
                    LabeledDropdown(
                        labelRes = R.string.label_species,
                        options = speciesList,
                        selected = species,
                        onSelected = { species = it },
                        modifier = Modifier.focusRequester(speciesFocus),
                        isError = speciesError != null,
                        supportingText = speciesError
                    )

                    LabeledDropdown(
                        labelRes = R.string.label_breed,
                        options = breedList,
                        selected = breed,
                        onSelected = { breed = it },
                        modifier = Modifier.focusRequester(breedFocus),
                        isError = breedError != null,
                        supportingText = breedError
                    )

                    Row(
                        horizontalArrangement = Arrangement.spacedBy(Dimentions.SMALL_PADDING_INPUT),
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        LabeledTextField(
                            labelRes = R.string.label_age,
                            value = age,
                            modifier = Modifier
                                .weight(1f)
                                .focusRequester(ageFocus),
                            onValueChange = { age = it },
                            keyboardType = KeyboardType.Number,
                            isError = ageError != null,
                            supportingText = ageError
                        )

                        LabeledTextField(
                            labelRes = R.string.label_milk_yield,
                            value = milkYield,
                            modifier = Modifier
                                .weight(1f)
                                .focusRequester(milkYieldFocus),
                            onValueChange = { milkYield = it },
                            keyboardType = KeyboardType.Number,
                            isError = milkYieldError != null,
                            supportingText = milkYieldError
                        )
                    }

                    LabeledTextField(
                        labelRes = R.string.label_calving_number,
                        value = calvingNumber,
                        modifier = Modifier
                            .fillMaxWidth()
                            .focusRequester(calvingNumberFocus),
                        onValueChange = { calvingNumber = it },
                        keyboardType = KeyboardType.Number,
                        isError = calvingNumberError != null,
                        supportingText = calvingNumberError
                    )

                    RadioGroup(
                        titleRes = R.string.label_reproductive_status,
                        options = reproList,
                        selected = reproductiveStatus,
                        onSelected = { reproductiveStatus = it },
                        isError = reproductiveStatusError != null
                    )
                    if (reproductiveStatusError != null) {
                        Text(
                            text = reproductiveStatusError ?: "",
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodySmall,
                            modifier = Modifier.padding(start = Dimentions.SMALL_PADDING_TEXT)
                        )
                    }

                    LabeledTextField(
                        labelRes = R.string.label_description,
                        value = description,
                        modifier = Modifier
                            .fillMaxWidth(),
                        onValueChange = { description = it },
                        keyboardType = KeyboardType.Text
                    )

                    Text(
                        text = stringResource(id = R.string.label_upload_media),
                        style = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        modifier = Modifier.padding(vertical = Dimentions.SMALL_PADDING_TEXT)
                    )
                }
            }
            
            items(silhouette.entries.toList()) { (key, value) ->
                ImageThumbnailButton(
                    image = photos[key],
                    onClick = { onTakePhoto(key) },
                    labelRes = value
                )
            }

            // Video Button
            item {
                VideoThumbnailButton(
                    videoSource = videoUri,
                    onClick = onTakeVideo
                )
            }

            // Save and Cancel Buttons
            item(span = { GridItemSpan(2) }) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = Dimentions.MEDIUM_PADDING_BUTTON),
                    horizontalArrangement = Arrangement.Center
                ) {
                    OutlinedButton(
                        onClick = onCancel,
                        modifier = Modifier
                            .weight(1f)
                            .padding(end = Dimentions.SMALL_PADDING_BUTTON)
                    ) {
                        Text(text = stringResource(id = R.string.btn_cancel))
                    }
                    Button(
                        onClick = onSave,
                        modifier = Modifier
                            .weight(1f)
                            .padding(start = Dimentions.SMALL_PADDING_BUTTON)
                    ) {
                        Text(text = stringResource(id = R.string.btn_save_profile))
                    }
                }
            }
            
            item(span = { GridItemSpan(2) }) {
                 Spacer(modifier = Modifier.height(Dimentions.LARGE_PADDING))
            }
        }
    }
}
