package com.example.livingai.pages.ratings

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavController
import com.example.livingai.R
import com.example.livingai.domain.model.AnimalRating
import com.example.livingai.pages.commons.Dimentions
import com.example.livingai.pages.components.RatingScale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RatingScreen(
    viewModel: RatingViewModel,
    navController: NavController? = null
) {
    val ratingState by viewModel.ratingState.collectAsState()

    if (ratingState == null) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
        return
    }
    
    var rating = ratingState!!

    // Define rating fields declaratively to avoid repeated code
    val ratingFields = remember {
        listOf(
            RatingField(
                labelRes = R.string.label_overall_rating,
                getter = { r -> r.overallRating },
                updater = { r, v -> r.copy(overallRating = v) }
            ),
            RatingField(
                labelRes = R.string.label_health_rating,
                getter = { r -> r.healthRating },
                updater = { r, v -> r.copy(healthRating = v) }
            ),
            RatingField(
                labelRes = R.string.label_breed_rating,
                getter = { r -> r.breedRating },
                updater = { r, v -> r.copy(breedRating = v) }
            ),

            RatingField(R.string.label_stature, { r -> r.stature }, { r, v -> r.copy(stature = v) }),
            RatingField(R.string.label_chest_width, { r -> r.chestWidth }, { r, v -> r.copy(chestWidth = v) }),
            RatingField(R.string.label_body_depth, { r -> r.bodyDepth }, { r, v -> r.copy(bodyDepth = v) }),
            RatingField(R.string.label_angularity, { r -> r.angularity }, { r, v -> r.copy(angularity = v) }),
            RatingField(R.string.label_rump_angle, { r -> r.rumpAngle }, { r, v -> r.copy(rumpAngle = v) }),
            RatingField(R.string.label_rump_width, { r -> r.rumpWidth }, { r, v -> r.copy(rumpWidth = v) }),
            RatingField(R.string.label_rear_leg_set, { r -> r.rearLegSet }, { r, v -> r.copy(rearLegSet = v) }),
            RatingField(R.string.label_rear_leg_rear_view, { r -> r.rearLegRearView }, { r, v -> r.copy(rearLegRearView = v) }),
            RatingField(R.string.label_foot_angle, { r -> r.footAngle }, { r, v -> r.copy(footAngle = v) }),

            RatingField(R.string.label_fore_udder_attachment, { r -> r.foreUdderAttachment }, { r, v -> r.copy(foreUdderAttachment = v) }),
            RatingField(R.string.label_rear_udder_height, { r -> r.rearUdderHeight }, { r, v -> r.copy(rearUdderHeight = v) }),
            RatingField(R.string.label_central_ligament, { r -> r.centralLigament }, { r, v -> r.copy(centralLigament = v) }),
            RatingField(R.string.label_udder_depth, { r -> r.udderDepth }, { r, v -> r.copy(udderDepth = v) }),
            RatingField(R.string.label_front_teat_position, { r -> r.frontTeatPosition }, { r, v -> r.copy(frontTeatPosition = v) }),
            RatingField(R.string.label_teat_length, { r -> r.teatLength }, { r, v -> r.copy(teatLength = v) }),
            RatingField(R.string.label_rear_teat_position, { r -> r.rearTeatPosition }, { r, v -> r.copy(rearTeatPosition = v) }),

            RatingField(R.string.label_locomotion, { r -> r.locomotion }, { r, v -> r.copy(locomotion = v) }),
            RatingField(R.string.label_body_condition_score, { r -> r.bodyConditionScore }, { r, v -> r.copy(bodyConditionScore = v) }),
            RatingField(R.string.label_hock_development, { r -> r.hockDevelopment }, { r, v -> r.copy(hockDevelopment = v) }),
            RatingField(R.string.label_bone_structure, { r -> r.boneStructure }, { r, v -> r.copy(boneStructure = v) }),
            RatingField(R.string.label_rear_udder_width, { r -> r.rearUdderWidth }, { r, v -> r.copy(rearUdderWidth = v) }),
            RatingField(R.string.label_teat_thickness, { r -> r.teatThickness }, { r, v -> r.copy(teatThickness = v) }),
            RatingField(R.string.label_muscularity, { r -> r.muscularity }, { r, v -> r.copy(muscularity = v) })
        )
    }

    Scaffold { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            item {
                OutlinedTextField(
                    value = rating.bodyConditionComments,
                    onValueChange = { 
                        rating = rating.copy(bodyConditionComments = it)
                        viewModel.onRatingChange(rating) 
                    },
                    label = { Text(stringResource(id = R.string.label_rating_comments)) },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 3
                )
            }

            items(ratingFields.size) { idx ->
                val field = ratingFields[idx]
                RatingScale(
                    label = field.labelRes,
                    value = field.getter(rating),
                    maxValue = 10,
                    onValueChange = { newVal ->
                        rating = field.updater(rating, newVal)
                        viewModel.onRatingChange(rating)
                    }
                )
            }

            item {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = Dimentions.MEDIUM_PADDING),
                    horizontalArrangement = Arrangement.spacedBy(Dimentions.MEDIUM_PADDING),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    OutlinedButton(
                        onClick = { navController?.popBackStack() },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(text = stringResource(id = R.string.btn_cancel))
                    }

                    Button(
                        onClick = {
                            viewModel.saveRatings()
                            navController?.popBackStack()
                        },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(text = stringResource(id = R.string.btn_save_ratings))
                    }
                }
            }
        }
    }
}

private data class RatingField(
    val labelRes: Int,
    val getter: (AnimalRating) -> Int,
    val updater: (AnimalRating, Int) -> AnimalRating
)
