package com.example.livingai.ui.page

import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.BitmapFactory
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.cardview.widget.CardView
import androidx.core.content.ContextCompat
import com.example.livingai.R
import com.example.livingai.storage.StorageUtils
import com.google.android.material.button.MaterialButton
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.io.File
import java.io.FileWriter

class GalleryActivity : AppCompatActivity() {

    private lateinit var container: LinearLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gallery)
        
        val toolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        
        toolbar.setNavigationOnClickListener {
            finish()
        }

        container = findViewById(R.id.galleryContainer)
        
        findViewById<FloatingActionButton>(R.id.fabAddCow).setOnClickListener {
            val intent = Intent(this, AddAnimalProfileActivity::class.java)
            startActivity(intent)
        }
        
        refreshGallery()
    }

    private fun refreshGallery() {
        container.removeAllViews()
        
        val imagesBaseFolder = StorageUtils.getImagesBaseFolder()
        val cowFolders = imagesBaseFolder.listFiles { file -> file.isDirectory } ?: emptyArray()
        
        val cowNamesFromFolders = cowFolders.map { it.name }

        val docsFolder = StorageUtils.getDocumentsFolder()
        val csvFile = File(docsFolder, "cow_profiles.csv")
        
        val cowDetails = if (csvFile.exists()) {
             csvFile.readLines().associate { line ->
                 val parts = line.split(",")
                 if (parts.isNotEmpty()) parts[0] to parts else "" to emptyList()
             }
        } else {
            emptyMap()
        }
        
        val allCowNames = (cowDetails.keys + cowNamesFromFolders).filter { it.isNotEmpty() && it != "CowID" }.distinct()

        allCowNames.forEach { cowName ->
            val details = cowDetails[cowName] ?: emptyList()
            val cowImageFolder = StorageUtils.getCowImageFolder(cowName)
            val cowFiles = cowImageFolder.listFiles { _, name -> name.endsWith(".jpg") }?.toList() ?: emptyList()
            
            addCowSection(cowName, cowFiles, details)
        }
    }

    private fun addCowSection(cowName: String, cowFiles: List<File>, details: List<String>) {
        // Main Card
        val card = CardView(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 0, 0, 24)
            }
            radius = 16 * resources.displayMetrics.density
            cardElevation = 2 * resources.displayMetrics.density
            setCardBackgroundColor(ContextCompat.getColor(context, R.color.surface_background))
        }

        // Horizontal Container (3:1 split)
        val horizontalContainer = LinearLayout(this).apply {
            orientation = LinearLayout.HORIZONTAL
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            weightSum = 4f
            setPadding(24, 24, 24, 24)
        }

        // Left Layout (Info) - Weight 3
        val leftLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                3f
            ).apply {
                marginEnd = 16
            }
        }

        val nameView = TextView(this).apply {
            text = if (details.isNotEmpty()) "${getString(R.string.text_cow_id)} $cowName" else cowName
            textSize = 20f
            setTypeface(null, android.graphics.Typeface.BOLD)
            setTextColor(ContextCompat.getColor(context, R.color.text_header_brown))
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                bottomMargin = 8
            }
        }
        leftLayout.addView(nameView)

        if (details.size >= 7) {
            // Translate values for display
            val displaySpecies = details.getOrElse(1) { "-" }
            val displayBreed = details.getOrElse(2) { "-" }
            val displayStatus = details.getOrElse(6) { "-" }
            
            val age = details.getOrElse(3) { "-" }
            val milk = details.getOrElse(4) { "-" }
            val calving = details.getOrElse(5) { "-" }

            val infoText = StringBuilder()
            infoText.append("${getString(R.string.label_species)} $displaySpecies   ")
            infoText.append("${getString(R.string.label_breed)} $displayBreed\n")
            infoText.append("${getString(R.string.label_age)} $age ${getString(R.string.unit_years)}   ")
            infoText.append("${getString(R.string.label_milk_yield)} $milk ${getString(R.string.unit_liters)}\n")
            infoText.append("${getString(R.string.label_calving_no)} $calving   ")
            infoText.append("${getString(R.string.label_status)} $displayStatus")

            val detailsView = TextView(this).apply {
                text = infoText.toString()
                textSize = 14f
                setTextColor(ContextCompat.getColor(context, R.color.text_brown))
                setLineSpacing(10f, 1f)
            }
            leftLayout.addView(detailsView)
        } else {
             val detailsView = TextView(this).apply {
                text = getString(R.string.text_no_details)
                textSize = 14f
                setTextColor(ContextCompat.getColor(context, R.color.text_brown))
            }
            leftLayout.addView(detailsView)
        }

        horizontalContainer.addView(leftLayout)

        // Right Layout (Buttons) - Weight 1
        val rightLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            layoutParams = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                1f
            )
            gravity = Gravity.CENTER_VERTICAL
        }

        val buttonParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            (48 * resources.displayMetrics.density).toInt()   
        ).apply {
            bottomMargin = (8 * resources.displayMetrics.density).toInt()
        }

        val editButton = MaterialButton(this).apply {
            text = getString(R.string.btn_edit)
            textSize = 12f
            setTypeface(null, android.graphics.Typeface.BOLD)
            setTextColor(ContextCompat.getColor(context, R.color.text_brown))
            cornerRadius = (12 * resources.displayMetrics.density).toInt()
            backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.brown_light_background))
            strokeWidth = (1 * resources.displayMetrics.density).toInt()
            strokeColor = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.text_brown))
            layoutParams = buttonParams
            insetTop = 0
            insetBottom = 0
            minHeight = 0
            minimumHeight = 0
            
            setOnClickListener {
                val intent = Intent(this@GalleryActivity, AddAnimalProfileActivity::class.java)
                intent.putExtra("COW_NAME", cowName)
                startActivity(intent)
            }
        }

        val rateButton = MaterialButton(this).apply {
            text = getString(R.string.btn_rate)
            textSize = 12f
            setTypeface(null, android.graphics.Typeface.BOLD)
            setTextColor(ContextCompat.getColor(context, R.color.white))
            cornerRadius = (12 * resources.displayMetrics.density).toInt()
            backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.earthy))
            layoutParams = buttonParams
            insetTop = 0
            insetBottom = 0
            minHeight = 0
            minimumHeight = 0
            
            setOnClickListener {
                val intent = Intent(this@GalleryActivity, RatingActivity::class.java)
                intent.putExtra("COW_NAME", cowName)
                startActivity(intent)
            }
        }
        
        val deleteButton = MaterialButton(this).apply {
            text = getString(R.string.btn_delete)
            textSize = 12f
            setTypeface(null, android.graphics.Typeface.BOLD)
            setTextColor(ContextCompat.getColor(context, R.color.white))
            cornerRadius = (12 * resources.displayMetrics.density).toInt()
            backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.shutter_red))
            layoutParams = buttonParams
            insetTop = 0
            insetBottom = 0
            minHeight = 0
            minimumHeight = 0
            
            setOnClickListener {
                deleteCow(cowName)
            }
        }

        rightLayout.addView(editButton)
        rightLayout.addView(rateButton)
        rightLayout.addView(deleteButton)
        horizontalContainer.addView(rightLayout)
        card.addView(horizontalContainer)
        
        container.addView(card)

        // Orientation Images
        if (cowFiles.isNotEmpty()) {
             // Instead of separating by orientation, put all images in a grid
             val gridLayout = android.widget.GridLayout(this).apply {
                columnCount = 3
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    setMargins(16, 0, 16, 16)
                }
            }
            
            // Sort images or keep them in order. The user asked for 3 in each row.
            cowFiles.forEach { file ->
                val thumbnailView = layoutInflater.inflate(R.layout.item_image_thumbnail, gridLayout, false)
                
                val imageView = thumbnailView.findViewById<ImageView>(R.id.ivThumbnail)
                val labelView = thumbnailView.findViewById<TextView>(R.id.tvOrientationLabel)
                val deleteButtonSmall = thumbnailView.findViewById<android.view.View>(R.id.btnDelete)
                
                // Optionally set layout params for thumbnailView to ensure 3 per row
                val displayMetrics = resources.displayMetrics
                val screenWidth = displayMetrics.widthPixels
                
                val itemWidth = (screenWidth - (48 * displayMetrics.density).toInt()) / 3
                thumbnailView.layoutParams = android.widget.GridLayout.LayoutParams().apply {
                    width = itemWidth
                    height = itemWidth // Square
                    setMargins(4, 4, 4, 4)
                }
                
                // Extract orientation from filename
                val parts = file.name.split("_")
                var orientation = ""
                if (parts.size >= 3) {
                    // Let's just try to find a known orientation in the filename
                    val orientations = listOf("left", "right", "angle", "front", "back", "leftangle", "rightangle")
                    orientation = orientations.find { file.name.contains("_${it}_") } ?: ""
                }
                
                val label = when(orientation) {
                    "front" -> getString(R.string.text_front_view)
                    "back" -> getString(R.string.text_rear_view)
                    "left" -> getString(R.string.text_left_side)
                    "right" -> getString(R.string.text_right_side)
                    "angle" -> getString(R.string.text_angle_view)
                    "leftangle" -> getString(R.string.text_left_angle)
                    "rightangle" -> getString(R.string.text_right_angle)
                    else -> orientation
                }
                
                labelView.text = label
                
                imageView.setImageBitmap(BitmapFactory.decodeFile(file.absolutePath))
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                
                imageView.setOnClickListener {
                    val intent = Intent(this@GalleryActivity, FullScreenImageActivity::class.java)
                    intent.putExtra("IMAGE_PATH", file.absolutePath)
                    startActivity(intent)
                }
                
                deleteButtonSmall.setOnClickListener {
                    if (file.delete()) {
                         val parentDir = file.parentFile
                        if (parentDir != null && parentDir.exists()) {
                            val remaining = parentDir.listFiles()
                            if (remaining == null || remaining.isEmpty()) {
                                parentDir.delete()
                            }
                        }
                        Toast.makeText(this@GalleryActivity, getString(R.string.toast_image_deleted), Toast.LENGTH_SHORT).show()
                        refreshGallery()
                    } else {
                        Toast.makeText(this@GalleryActivity, getString(R.string.toast_error_deleting_image), Toast.LENGTH_SHORT).show()
                    }
                }
                
                gridLayout.addView(thumbnailView)
            }
            container.addView(gridLayout)
            
             val separator = android.view.View(this).apply {
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    2
                ).apply {
                    setMargins(0, 16, 0, 16)
                }
                setBackgroundColor(android.graphics.Color.LTGRAY)
            }
            container.addView(separator)
        }
    }
    
    private fun deleteCow(cowName: String) {
        // Delete Images
        val imageFolder = StorageUtils.getCowImageFolder(cowName)
        if (imageFolder.exists()) {
            imageFolder.deleteRecursively()
        }
        
        val docsFolder = StorageUtils.getDocumentsFolder()
        
        // Delete Profile
        val profileFile = File(docsFolder, "cow_profiles.csv")
        if (profileFile.exists()) {
            val lines = profileFile.readLines()
            val newLines = lines.filter { !it.startsWith("$cowName,") }
            FileWriter(profileFile).use { writer ->
                newLines.forEach { writer.write(it + "\n") }
            }
        }
        
        // Delete Ratings
        val ratingsFile = File(docsFolder, "cow_ratings.csv")
        if (ratingsFile.exists()) {
            val lines = ratingsFile.readLines()
            val newLines = lines.filter { !it.startsWith("$cowName,") }
            FileWriter(ratingsFile).use { writer ->
                newLines.forEach { writer.write(it + "\n") }
            }
        }
        
        Toast.makeText(this, getString(R.string.toast_profile_deleted), Toast.LENGTH_SHORT).show()
        refreshGallery()
    }
    
    override fun onResume() {
        super.onResume()
        refreshGallery()
    }
}