package com.example.livingai.ui.page

import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import com.example.livingai.R
import com.example.livingai.storage.StorageUtils
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputLayout
import java.io.File
import java.io.FileWriter
import java.util.Locale

class RatingActivity : AppCompatActivity() {

    private lateinit var currentCowName: String
    private lateinit var ratingsContainer: LinearLayout
    
    // Feature list (internal keys)
    private val features = listOf(
        "Stature", "Chest width", "Body depth", "Angularity", 
        "Rump angle", "Rump width", "Rear legs set", "Rear legs rear view", 
        "Foot angle", "Fore udder attachment", "Rear udder height", 
        "Central ligament", "Udder depth", "Front teat position", 
        "Teat length", "Rear teat position", "Locomotion", 
        "Body condition score", "Hock development", "Bone structure", 
        "Rear udder width", "Teat thickness", "Muscularity"
    )
    
    private val ratingsMap = mutableMapOf<String, Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rating)

        currentCowName = intent.getStringExtra("COW_NAME") ?: run {
            finish()
            return
        }

        val toolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        toolbar.setNavigationOnClickListener { finish() }
        findViewById<TextView>(R.id.tvToolbarTitle)?.text = getString(R.string.title_rate_cow)

        setupUIStrings()
        loadCowDetails()
        loadCowImages()
        setupRatingSection()
        loadExistingRatings()

        findViewById<MaterialButton>(R.id.btnSaveRating).setOnClickListener {
            saveRatings()
        }
        
        findViewById<MaterialButton>(R.id.btnCancelRating).setOnClickListener {
            finish()
        }
    }
    
    private fun setupUIStrings() {
        findViewById<TextView>(R.id.tvHeaderPhotos)?.text = getString(R.string.header_photos)
        findViewById<TextView>(R.id.tvHeaderCowDetails)?.text = getString(R.string.header_cow_details)
        findViewById<TextView>(R.id.tvHeaderFeatureRatings)?.text = getString(R.string.header_feature_ratings)
        findViewById<TextInputLayout>(R.id.tilComments)?.hint = getString(R.string.hint_comments)
        findViewById<MaterialButton>(R.id.btnSaveRating)?.text = getString(R.string.btn_save_rating)
        findViewById<MaterialButton>(R.id.btnCancelRating)?.text = getString(R.string.btn_cancel)
    }

    private fun loadCowDetails() {
        val docsFolder = StorageUtils.getDocumentsFolder()
        val csvFile = File(docsFolder, "cow_profiles.csv")
        if (!csvFile.exists()) return

        try {
            val lines = csvFile.readLines()
            val record = lines.find { it.startsWith("$currentCowName,") }?.split(",") ?: return

            if (record.size >= 8) {
                val displaySpecies = record[1]
                val displayBreed = record[2]
                val displayStatus = record[6]
                
                val infoText = StringBuilder()
                infoText.append("${getString(R.string.label_species)} $displaySpecies\n")
                infoText.append("${getString(R.string.label_breed)} $displayBreed\n")
                infoText.append("${getString(R.string.label_age)} ${record[3]} ${getString(R.string.unit_years)}\n")
                infoText.append("${getString(R.string.label_milk_yield)} ${record[4]} ${getString(R.string.unit_liters)}\n")
                infoText.append("${getString(R.string.label_calving_no)} ${record[5]}\n")
                infoText.append("${getString(R.string.label_status)} $displayStatus\n")
                infoText.append("${getString(R.string.hint_description)}: ${record[7]}")

                findViewById<TextView>(R.id.tvCowDetails).text = infoText.toString()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    private fun loadCowImages() {
        val container = findViewById<LinearLayout>(R.id.ratingImagesContainer) ?: return
        container.removeAllViews()
        
        val cowImagesFolder = StorageUtils.getCowImageFolder(currentCowName)
        val files = cowImagesFolder.listFiles { _, name -> name.startsWith("${currentCowName}_") && name.endsWith(".jpg") } ?: return
        
        val horizontalScroll = android.widget.HorizontalScrollView(this)
        horizontalScroll.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        horizontalScroll.isFillViewport = false
        
        val imagesLayout = LinearLayout(this)
        imagesLayout.orientation = LinearLayout.HORIZONTAL
        
        files.forEach { file ->
            val imageView = ImageView(this)
            val size = (100 * resources.displayMetrics.density).toInt()
            val params = LinearLayout.LayoutParams(size, size)
            params.setMargins(0, 0, 16, 0)
            imageView.layoutParams = params
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            
            val bitmap = BitmapFactory.decodeFile(file.absolutePath)
            imageView.setImageBitmap(bitmap)
            
            imageView.setOnClickListener {
                val intent = Intent(this, FullScreenImageActivity::class.java)
                intent.putExtra("IMAGE_PATH", file.absolutePath)
                startActivity(intent)
            }
            
            imagesLayout.addView(imageView)
        }
        
        horizontalScroll.addView(imagesLayout)
        container.addView(horizontalScroll)
    }

    private fun setupRatingSection() {
        ratingsContainer = findViewById(R.id.ratingsContainer)
        ratingsContainer.removeAllViews()

        val textColor = ContextCompat.getColor(this, R.color.text_brown)

        features.forEach { feature ->
            val featureView = layoutInflater.inflate(R.layout.item_feature_rating, ratingsContainer, false)
            
            val key = "feature_" + feature.lowercase(Locale.ROOT).replace(" ", "_")
            val resourceId = resources.getIdentifier(key, "string", packageName)
            val displayName = if (resourceId != 0) getString(resourceId) else feature
            
            featureView.findViewById<TextView>(R.id.tvFeatureName).text = displayName
            
            val buttonContainer = featureView.findViewById<LinearLayout>(R.id.buttonContainer)
            val segmentViews = mutableListOf<TextView>()
            
            for (i in 1..9) {
                val tv = TextView(this)
                val params = LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    1f
                )
                tv.layoutParams = params
                tv.text = i.toString()
                tv.gravity = Gravity.CENTER
                tv.setTextColor(textColor)
                tv.textSize = 14f
                tv.setBackgroundColor(Color.TRANSPARENT)
                
                tv.setOnClickListener {
                    val currentRating = ratingsMap[feature] ?: 0
                    if (currentRating == i) {
                        ratingsMap[feature] = 0
                        updateSegmentSelection(segmentViews, 0)
                    } else {
                        ratingsMap[feature] = i
                        updateSegmentSelection(segmentViews, i)
                    }
                }
                
                segmentViews.add(tv)
                buttonContainer.addView(tv)
            }
            
            featureView.tag = segmentViews
            ratingsContainer.addView(featureView)
        }
    }

    private fun updateSegmentSelection(segments: List<TextView>, selectedRating: Int) {
        val selectedColor = ContextCompat.getColor(this, R.color.earthy)
        val textColorUnselected = ContextCompat.getColor(this, R.color.text_brown)
        
        segments.forEachIndexed { index, tv ->
            val rating = index + 1
            if (rating == selectedRating) {
                tv.setTextColor(Color.WHITE)
                
                val radius = (8 * resources.displayMetrics.density)
                val drawable = GradientDrawable()
                drawable.setColor(selectedColor)
                
                when (rating) {
                    1 -> drawable.cornerRadii = floatArrayOf(radius, radius, 0f, 0f, 0f, 0f, radius, radius)
                    9 -> drawable.cornerRadii = floatArrayOf(0f, 0f, radius, radius, radius, radius, 0f, 0f)
                    else -> drawable.cornerRadius = 0f
                }
                tv.background = drawable
            } else {
                tv.setTextColor(textColorUnselected)
                tv.background = null
            }
        }
    }

    private fun loadExistingRatings() {
        val docsFolder = StorageUtils.getDocumentsFolder()
        val ratingsFile = File(docsFolder, "cow_ratings.csv")
        if (!ratingsFile.exists()) return

        try {
            val lines = ratingsFile.readLines()
            val record = lines.find { it.startsWith("$currentCowName,") }?.split(",") ?: return
            
            if (record.size >= 2) {
                val comments = record[1].replace(";", ",")
                findViewById<TextInputLayout>(R.id.tilComments).editText?.setText(comments)
                
                features.forEachIndexed { index, feature ->
                    val ratingStr = record.getOrNull(index + 2)
                    val rating = ratingStr?.toIntOrNull() ?: 0
                    
                    if (rating > 0) {
                        ratingsMap[feature] = rating
                        
                        val featureView = ratingsContainer.getChildAt(index)
                        if (featureView != null) {
                            @Suppress("UNCHECKED_CAST")
                            val segments = featureView.tag as? List<TextView>
                            segments?.let { updateSegmentSelection(it, rating) }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun saveRatings() {
        val commentsInput = findViewById<TextInputLayout>(R.id.tilComments).editText?.text.toString()
        val comments = commentsInput.replace(",", ";")
        
        val docsFolder = StorageUtils.getDocumentsFolder()
        val ratingsFile = File(docsFolder, "cow_ratings.csv")
        
        val headerBuilder = StringBuilder("CowID,Comments")
        features.forEach { headerBuilder.append(",$it") }
        val header = headerBuilder.toString()
        
        val rowBuilder = StringBuilder()
        rowBuilder.append("$currentCowName,$comments")
        features.forEach { feature ->
            val rating = ratingsMap[feature] ?: 0
            rowBuilder.append(",$rating")
        }
        val newRow = rowBuilder.toString()
        
        try {
            val lines = if (ratingsFile.exists()) ratingsFile.readLines().toMutableList() else mutableListOf()
            
            if (lines.isEmpty()) {
                lines.add(header)
            }

            val existingIndex = lines.indexOfFirst { it.startsWith("$currentCowName,") }
            
            if (existingIndex != -1) {
                lines[existingIndex] = newRow
            } else {
                lines.add(newRow)
            }
            
            FileWriter(ratingsFile).use { writer ->
                lines.forEach { line ->
                    writer.write(line + "\n")
                }
            }

            Toast.makeText(this, getString(R.string.toast_ratings_saved), Toast.LENGTH_SHORT).show()
            finish()
        } catch (e: Exception) {
            Toast.makeText(this, getString(R.string.toast_error_saving_ratings), Toast.LENGTH_SHORT).show()
        }
    }
}
