package com.example.livingai.ui.page

import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.SeekBar
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.example.livingai.R
import com.example.livingai.commons.Constants
import com.google.android.material.button.MaterialButton
import com.google.android.material.switchmaterial.SwitchMaterial
import java.util.Locale

class HomeActivity : AppCompatActivity() {
    
    companion object {
        const val ALGORITHM_HAMMING = Constants.ALGORITHM_HAMMING
        const val ALGORITHM_EUCLIDEAN = Constants.ALGORITHM_EUCLIDEAN
        const val ALGORITHM_JACCARD = Constants.ALGORITHM_JACCARD
        private const val PERMISSION_REQUEST_CODE = 101
        const val PREF_COW_ILLUSTRATION_INDEX = Constants.PREF_COW_ILLUSTRATION_INDEX
        const val PREF_AUTO_CAPTURE = Constants.PREF_AUTO_CAPTURE
        const val PREF_DEBUG_ENABLE = Constants.PREF_DEBUG_ENABLE
        const val PREF_MASK_DISPLAY = Constants.PREF_MASK_DISPLAY
        var IS_RELEASE_BUILD = true // Set to true for release
    }
    
    private val internalAlgorithms = listOf(ALGORITHM_HAMMING, ALGORITHM_EUCLIDEAN, ALGORITHM_JACCARD)

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

        setupUI()
        checkAndRequestPermissions()
    }

    private fun checkAndRequestPermissions() {
        val permissions = mutableListOf<String>()
        
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(android.Manifest.permission.CAMERA)
        }
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+: Request All Files Access for managing external storage
            if (!android.os.Environment.isExternalStorageManager()) {
                try {
                    val intent = Intent(android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    val uri = android.net.Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                } catch (_: Exception) {
                    val intent = Intent(android.provider.Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                    startActivity(intent)
                }
            }
        } else {
            // Android 10 and below
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }

        if (permissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissions.toTypedArray(), PERMISSION_REQUEST_CODE)
        }
    }
    
    private fun setupUI() {
        val prefs = getSharedPreferences("AnimalRatingPrefs", MODE_PRIVATE)
        
        // Menu Button Logic
        val drawerLayout = findViewById<DrawerLayout>(R.id.drawer_layout)
        val btnMenu = findViewById<ImageButton>(R.id.btnMenu)
        btnMenu?.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }
        
        // Language Spinner
        val languageSpinner = findViewById<Spinner>(R.id.spinnerLanguage)
        val languages = listOf("English", "Hindi")
        val languageAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
        languageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        languageSpinner.adapter = languageAdapter
        
        val savedLang = prefs.getString("LANGUAGE", "English")
        languageSpinner.setSelection(languages.indexOf(savedLang))
        
        languageSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selectedLanguage = languages[position]
                val currentLang = prefs.getString("LANGUAGE", "English")

                if (selectedLanguage != currentLang) {
                    saveSettings()
                    setLanguage(selectedLanguage)
                    android.os.Handler(android.os.Looper.getMainLooper()).post {
                        recreate()
                    }
                }
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        
        // Set text from R.string
        findViewById<TextView>(R.id.tvTitle).text = getString(R.string.app_name)
        findViewById<TextView>(R.id.tvSubtitle).text = getString(R.string.subtitle_home)
        findViewById<MaterialButton>(R.id.btnViewGallery).text = getString(R.string.btn_view_gallery)
        findViewById<MaterialButton>(R.id.btnSelectCow).text = getString(R.string.btn_select_cow)
        findViewById<TextView>(R.id.tvAlgorithmLabel).text = getString(R.string.label_algorithm)
        findViewById<TextView>(R.id.tvThresholdLabel).text = getString(R.string.label_match_threshold)

        // Cow Illustration and Logic
        val ivCowIllustration = findViewById<ImageView>(R.id.ivCowIllustration)
        val savedIndex = prefs.getInt(PREF_COW_ILLUSTRATION_INDEX, 4)
        setCowIllustration(ivCowIllustration, savedIndex)

        ivCowIllustration.setOnClickListener { view ->
            showIllustrationPopup(view, ivCowIllustration)
        }

        // Navigation buttons
        findViewById<MaterialButton>(R.id.btnViewGallery).setOnClickListener {
            startActivity(Intent(this, GalleryActivity::class.java))
        }

        findViewById<MaterialButton>(R.id.btnSelectCow).setOnClickListener {
            if (!IS_RELEASE_BUILD) {
                saveSettings()
            }
            startActivity(Intent(this, AddAnimalProfileActivity::class.java))
        }

        // Auto Capture Toggle
        val switchAutoCapture = findViewById<SwitchMaterial>(R.id.switchAutoCapture)
        switchAutoCapture.text = getString(R.string.label_auto_capture)
        val autoCaptureEnabled = prefs.getBoolean(PREF_AUTO_CAPTURE, false)
        switchAutoCapture.isChecked = autoCaptureEnabled

        val states = arrayOf(
            intArrayOf(android.R.attr.state_checked),
            intArrayOf(-android.R.attr.state_checked)
        )
        val thumbColors = intArrayOf(
            ContextCompat.getColor(this, R.color.earthy), // Dark Brown for On
            Color.GRAY // Grey for Off
        )
        val trackColors = intArrayOf(
            ContextCompat.getColor(this, R.color.switch_track_brown), // Lighter Brown for On track
            Color.LTGRAY // Light Grey for Off track
        )

        switchAutoCapture.thumbTintList = ColorStateList(states, thumbColors)
        switchAutoCapture.trackTintList = ColorStateList(states, trackColors)

        switchAutoCapture.setOnCheckedChangeListener { _, isChecked ->
            prefs.edit().putBoolean(PREF_AUTO_CAPTURE, isChecked).apply()
        }

        val switchEnableDebug = findViewById<SwitchMaterial>(R.id.switchEnableDebug)
        switchEnableDebug.text = getString(R.string.label_enable_debug)
        val debugEnabled = prefs.getBoolean(PREF_DEBUG_ENABLE, false)
        switchEnableDebug.isChecked = debugEnabled
        IS_RELEASE_BUILD = !debugEnabled

        switchEnableDebug.thumbTintList = ColorStateList(states, thumbColors)
        switchEnableDebug.trackTintList = ColorStateList(states, trackColors)

        switchEnableDebug.setOnCheckedChangeListener { _, isChecked ->
            prefs.edit().putBoolean(PREF_DEBUG_ENABLE, isChecked).apply()
            IS_RELEASE_BUILD = !isChecked
            if (IS_RELEASE_BUILD) {
                findViewById<CardView>(R.id.viewSettings).visibility = View.GONE
            } else {
                saveSettings()
                findViewById<CardView>(R.id.viewSettings).visibility = View.VISIBLE
            }
        }

        val headerSettings = findViewById<TextView>(R.id.tvHeaderSettings)
        if (headerSettings != null) headerSettings.text = getString(R.string.header_settings)

        // Algorithm Spinner
        val spinner = findViewById<Spinner>(R.id.spinnerAlgorithm)

        val displayAlgorithms = listOf(
            getString(R.string.algo_hamming),
            getString(R.string.algo_euclidean),
            getString(R.string.algo_jaccard)
        )

        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, displayAlgorithms)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = adapter

        // Set default selection from preferences or intent
        val savedAlg = prefs.getString("ALGORITHM", ALGORITHM_HAMMING)
        val index = internalAlgorithms.indexOf(savedAlg)
        spinner.setSelection(if (index >= 0) index else 0)

        // Threshold SeekBar
        val seekBar = findViewById<SeekBar>(R.id.seekBarThreshold)
        val tvThreshold = findViewById<TextView>(R.id.tvThresholdValue)

        val savedThreshold = prefs.getInt("THRESHOLD", 75)
        seekBar.progress = savedThreshold
        tvThreshold.text = "$savedThreshold%"

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                tvThreshold.text = "$progress%"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // Mask Display Toggle
        val switchMaskDisplay = findViewById<SwitchMaterial>(R.id.switchMaskDisplay)
        switchMaskDisplay.text = getString(R.string.label_mask_display)
        val maskDisplayEnabled = prefs.getBoolean(PREF_MASK_DISPLAY, false)
        switchMaskDisplay.isChecked = maskDisplayEnabled

        switchMaskDisplay.thumbTintList = ColorStateList(states, thumbColors)
        switchMaskDisplay.trackTintList = ColorStateList(states, trackColors)

        switchMaskDisplay.setOnCheckedChangeListener { _, isChecked ->
            prefs.edit().putBoolean(PREF_MASK_DISPLAY, isChecked).apply()
        }

        // Initial visibility based on IS_RELEASE_BUILD
        if (IS_RELEASE_BUILD) {
            val settingsView = findViewById<CardView>(R.id.viewSettings)
            settingsView.visibility = View.GONE
        } else {
             findViewById<CardView>(R.id.viewSettings).visibility = View.VISIBLE
        }
    }
    
    private fun setLanguage(language: String) {
        val prefs = getSharedPreferences("AnimalRatingPrefs", MODE_PRIVATE)
        prefs.edit().putString("LANGUAGE", language).apply()
        
        val localeCode = when(language) {
            "Hindi" -> "hi"
            "Gujarati" -> "gu"
            else -> "en"
        }
        
        val locale = Locale(localeCode)
        Locale.setDefault(locale)
        val config = resources.configuration
        config.setLocale(locale)
        createConfigurationContext(config)
        resources.updateConfiguration(config, resources.displayMetrics)
    }
    
    private fun showIllustrationPopup(anchor: View, imageView: ImageView) {
        val popup = PopupMenu(this, anchor)
        for (i in 0..4) {
            popup.menu.add(0, i, i, "Illustration $i")
        }
        
        popup.setOnMenuItemClickListener { item ->
            val index = item.itemId
            setCowIllustration(imageView, index)
            
            // Save preference
            getSharedPreferences("AnimalRatingPrefs", MODE_PRIVATE).edit()
                .putInt(PREF_COW_ILLUSTRATION_INDEX, index)
                .apply()
            true
        }
        popup.show()
    }
    
    private fun setCowIllustration(imageView: ImageView, index: Int) {
        val resName = "cow_illustration_$index"
        val resId = resources.getIdentifier(resName, "drawable", packageName)
        
        if (resId != 0) {
            imageView.setImageResource(resId)
        } else {
             if (index == 0) {
                 val defaultId = resources.getIdentifier("cow_illustration", "drawable", packageName)
                 if (defaultId != 0) imageView.setImageResource(defaultId)
             }
        }
    }

    private fun saveSettings() {
        val spinner = findViewById<Spinner>(R.id.spinnerAlgorithm)
        val seekBar = findViewById<SeekBar>(R.id.seekBarThreshold)
        val showSegmentationMask = findViewById<SwitchMaterial>(R.id.switchMaskDisplay)

        if (spinner != null && seekBar != null && showSegmentationMask != null) {
            val selectedIndex = spinner.selectedItemPosition
            val selectedAlgorithm = if (selectedIndex >= 0 && selectedIndex < internalAlgorithms.size) {
                internalAlgorithms[selectedIndex]
            } else {
                ALGORITHM_HAMMING
            }

            val threshold = seekBar.progress

            // Save to preferences
            val prefs = getSharedPreferences("AnimalRatingPrefs", MODE_PRIVATE)
            val showMask = showSegmentationMask.isChecked
            prefs.edit().apply {
                putString("ALGORITHM", selectedAlgorithm)
                putInt("THRESHOLD", threshold)
                putBoolean(PREF_MASK_DISPLAY, showMask)
                apply()
            }
        }
    }

    private fun saveSettingsAndStart() {
        if(!IS_RELEASE_BUILD)
            saveSettings()
        startActivity(Intent(this, AddAnimalProfileActivity::class.java))
    }
}