package com.rugvedsarika.areacalc

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageButton
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.ViewModelProvider
import android.view.animation.AnticipateInterpolator
import android.animation.ObjectAnimator
import androidx.core.animation.doOnEnd
import android.os.Handler
import android.os.Looper
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: MainViewModel
    private lateinit var etInput: TextInputEditText
    private lateinit var etRate: TextInputEditText
    private lateinit var spinnerFrom: Spinner
    private lateinit var spinnerTo: Spinner
    private lateinit var btnSwap: ImageButton
    private lateinit var tvResult: TextView
    private lateinit var tvTotalPrice: TextView
    private lateinit var btnCopy: MaterialButton
    private lateinit var btnShare: MaterialButton
    private lateinit var btnSave: MaterialButton
    
    private lateinit var historyManager: HistoryManager
    private lateinit var preferenceHelper: PreferenceHelper
    private var isContentReady = false

    override fun onCreate(savedInstanceState: Bundle?) {
        val splashScreen = installSplashScreen()
        
        // Keep splash screen on for at least 1 second
        splashScreen.setKeepOnScreenCondition { !isContentReady }
        Handler(Looper.getMainLooper()).postDelayed({
            isContentReady = true
        }, 1200)

        // Custom exit animation
        splashScreen.setOnExitAnimationListener { splashScreenView ->
            val slideUp = ObjectAnimator.ofFloat(
                splashScreenView.view,
                View.TRANSLATION_Y,
                0f,
                -splashScreenView.view.height.toFloat()
            )
            slideUp.interpolator = AnticipateInterpolator()
            slideUp.duration = 500L
            slideUp.doOnEnd { splashScreenView.remove() }
            slideUp.start()
        }

        preferenceHelper = PreferenceHelper(this)
        // Apply saved theme before setContentView
        AppCompatDelegate.setDefaultNightMode(preferenceHelper.getThemeMode())
        
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setSupportActionBar(findViewById(R.id.toolbar))

        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        historyManager = HistoryManager(this)
        historyManager.addDummyDataIfEmpty()

        initViews()
        setupSpinners()
        setupListeners()
        observeViewModel()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_history -> {
                showHistoryDialog()
                true
            }
            R.id.action_theme -> {
                toggleTheme()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun toggleTheme() {
        val currentMode = preferenceHelper.getThemeMode()
        val newMode = if (currentMode == AppCompatDelegate.MODE_NIGHT_YES) {
            AppCompatDelegate.MODE_NIGHT_NO
        } else {
            AppCompatDelegate.MODE_NIGHT_YES
        }
        
        preferenceHelper.setThemeMode(newMode)
        AppCompatDelegate.setDefaultNightMode(newMode)
    }

    private fun initViews() {
        etInput = findViewById(R.id.etInput)
        etRate = findViewById(R.id.etRate)
        spinnerFrom = findViewById(R.id.spinnerFrom)
        spinnerTo = findViewById(R.id.spinnerTo)
        btnSwap = findViewById(R.id.btnSwap)
        tvResult = findViewById(R.id.tvResult)
        tvTotalPrice = findViewById(R.id.tvTotalPrice)
        btnCopy = findViewById(R.id.btnCopy)
        btnShare = findViewById(R.id.btnShare)
        btnSave = findViewById(R.id.btnSave)
    }

    private fun setupSpinners() {
        val unitNames = AreaUnit.getNames(this)
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, unitNames)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        spinnerFrom.adapter = adapter
        spinnerTo.adapter = adapter

        // Set initial selections based on ViewModel's default values
        viewModel.fromUnit.value?.let { unit ->
            val position = adapter.getPosition(getString(unit.nameResId))
            if (position >= 0) spinnerFrom.setSelection(position)
        }
        
        viewModel.toUnit.value?.let { unit ->
            val position = adapter.getPosition(getString(unit.nameResId))
            if (position >= 0) spinnerTo.setSelection(position)
        }
    }

    private fun setupListeners() {
        etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                viewModel.onInputValueChanged(s.toString())
            }
            override fun afterTextChanged(s: Editable?) {}
        })
        
        etRate.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                viewModel.onRateValueChanged(s.toString())
            }
            override fun afterTextChanged(s: Editable?) {}
        })

        spinnerFrom.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selected = parent?.getItemAtPosition(position) as String
                AreaUnit.fromDisplayName(this@MainActivity, selected)?.let {
                    viewModel.setFromUnit(it)
                }
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        spinnerTo.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selected = parent?.getItemAtPosition(position) as String
                AreaUnit.fromDisplayName(this@MainActivity, selected)?.let {
                    viewModel.setToUnit(it)
                }
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        btnSwap.setOnClickListener {
            viewModel.swapUnits()
        }

        btnCopy.setOnClickListener {
            val result = tvResult.text.toString()
            if (result.isNotEmpty() && result != "0") {
                val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                val clip = ClipData.newPlainText("Area Result", result)
                clipboard.setPrimaryClip(clip)
                Toast.makeText(this, getString(R.string.copied_to_clipboard), Toast.LENGTH_SHORT).show()
            }
        }

        btnShare.setOnClickListener {
            shareResult()
        }
        
        btnSave.setOnClickListener {
            saveToHistory()
        }
    }

    private fun observeViewModel() {
        viewModel.result.observe(this) { result ->
            tvResult.text = result
        }
        
        viewModel.totalPrice.observe(this) { price ->
            tvTotalPrice.text = getString(R.string.total_price, "$price ${getString(R.string.currency_symbol)}")
        }

        viewModel.fromUnit.observe(this) { unit ->
            val adapter = spinnerFrom.adapter as ArrayAdapter<String>
            val position = adapter.getPosition(getString(unit.nameResId))
            if (spinnerFrom.selectedItemPosition != position) {
                spinnerFrom.setSelection(position)
            }
        }

        viewModel.toUnit.observe(this) { unit ->
            val adapter = spinnerTo.adapter as ArrayAdapter<String>
            val position = adapter.getPosition(getString(unit.nameResId))
            if (spinnerTo.selectedItemPosition != position) {
                spinnerTo.setSelection(position)
            }
        }
    }
    
    private fun shareResult() {
        val result = tvResult.text.toString()
        val input = etInput.text.toString()
        val from = spinnerFrom.selectedItem.toString()
        val to = spinnerTo.selectedItem.toString()
        
        if (result.isNotEmpty() && result != "0" && input.isNotEmpty()) {
            val shareText = "$input $from = $result $to\n\nConverted via AreaCalc App"
            val sendIntent: Intent = Intent().apply {
                action = Intent.ACTION_SEND
                putExtra(Intent.EXTRA_TEXT, shareText)
                type = "text/plain"
            }
            val shareIntent = Intent.createChooser(sendIntent, null)
            startActivity(shareIntent)
        }
    }
    
    private fun saveToHistory() {
        val result = tvResult.text.toString()
        val input = etInput.text.toString()
        val from = spinnerFrom.selectedItem.toString()
        val to = spinnerTo.selectedItem.toString()
        
        if (result.isNotEmpty() && result != "0" && input.isNotEmpty()) {
            val item = HistoryItem(input, from, to, result)
            historyManager.saveConversion(item)
            Toast.makeText(this, getString(R.string.history_saved), Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showHistoryDialog() {
        val historyList = historyManager.getHistory()
        if (historyList.isEmpty()) {
            Toast.makeText(this, getString(R.string.no_history), Toast.LENGTH_SHORT).show()
            return
        }
        
        val displayList = historyList.map { 
            "${it.input} ${it.fromUnit} -> ${it.result} ${it.toUnit}" 
        }.toTypedArray()
        
        AlertDialog.Builder(this)
            .setTitle(getString(R.string.history))
            .setItems(displayList, null)
            .setPositiveButton(getString(android.R.string.ok), null)
            .setNeutralButton(getString(R.string.clear_history)) { _, _ ->
                historyManager.clearHistory()
                Toast.makeText(this, "History Cleared", Toast.LENGTH_SHORT).show()
            }
            .show()
    }
}
