package com.obdwidgets.ui

import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.obdwidgets.databinding.ActivityWidgetConfigBinding
import com.obdwidgets.model.OBDParameter
import com.obdwidgets.model.WidgetConfig
import com.obdwidgets.model.WidgetType
import com.obdwidgets.widget.OBDWidgetProvider

class WidgetConfigurationActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityWidgetConfigBinding
    private var widgetId = AppWidgetManager.INVALID_APPWIDGET_ID
    private var isFirstParameterSelection = true
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWidgetConfigBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        setResult(Activity.RESULT_CANCELED)
        
        widgetId = intent.getIntExtra(
            AppWidgetManager.EXTRA_APPWIDGET_ID,
            AppWidgetManager.INVALID_APPWIDGET_ID
        )
        
        if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish()
            return
        }
        
        val existingConfig = OBDWidgetProvider.loadWidgetConfig(this, widgetId)
        
        setupWidgetTypeSpinner(existingConfig?.getWidgetType() ?: WidgetType.ANALOG)
        setupParameterSpinner(existingConfig?.getParameter() ?: OBDParameter.SPEED)
        setupValueInputs(existingConfig)
        
        binding.buttonSave.setOnClickListener {
            saveConfiguration()
        }
    }
    
    private fun setupWidgetTypeSpinner(selectedType: WidgetType) {
        val types = WidgetType.values().map { it.name }
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, types)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinnerWidgetType.adapter = adapter
        binding.spinnerWidgetType.setSelection(WidgetType.values().indexOf(selectedType))
    }
    
    private fun setupParameterSpinner(selectedParameter: OBDParameter) {
        val parameters = OBDParameter.values().map { it.displayName }
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, parameters)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinnerParameter.adapter = adapter
        
        isFirstParameterSelection = true
        binding.spinnerParameter.setSelection(OBDParameter.values().indexOf(selectedParameter))
        
        binding.spinnerParameter.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                if (isFirstParameterSelection) {
                    isFirstParameterSelection = false
                    return
                }
                val parameter = OBDParameter.values()[position]
                binding.editMinValue.setText(parameter.minValue.toString())
                binding.editMaxValue.setText(parameter.maxValue.toString())
                binding.textUnit.text = parameter.unit
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }
    
    private fun setupValueInputs(config: WidgetConfig?) {
        if (config != null) {
            binding.editMinValue.setText(config.minValue.toString())
            binding.editMaxValue.setText(config.maxValue.toString())
            binding.editCustomLabel.setText(config.customLabel ?: "")
            binding.textUnit.text = config.getParameter().unit
            binding.editLabelColor.setText(String.format("#%06X", 0xFFFFFF and config.labelColor))
            binding.editValueColor.setText(String.format("#%06X", 0xFFFFFF and config.valueColor))
            binding.editNeedleColor.setText(String.format("#%06X", 0xFFFFFF and config.needleColor))
            binding.editScaleColor.setText(String.format("#%06X", 0xFFFFFF and config.scaleColor))
            binding.editFontSize.setText(config.valueFontSize.toString())
        } else {
            val defaultParam = OBDParameter.SPEED
            binding.editMinValue.setText(defaultParam.minValue.toString())
            binding.editMaxValue.setText(defaultParam.maxValue.toString())
            binding.textUnit.text = defaultParam.unit
            binding.editLabelColor.setText("#CCCCCC")
            binding.editValueColor.setText("#FFFFFF")
            binding.editNeedleColor.setText("#FF0000")
            binding.editScaleColor.setText("#FFFFFF")
            binding.editFontSize.setText("48")
        }
    }
    
    private fun saveConfiguration() {
        val widgetType = WidgetType.values()[binding.spinnerWidgetType.selectedItemPosition]
        val parameter = OBDParameter.values()[binding.spinnerParameter.selectedItemPosition]
        
        val minValue = binding.editMinValue.text.toString().toFloatOrNull() ?: parameter.minValue
        val maxValue = binding.editMaxValue.text.toString().toFloatOrNull() ?: parameter.maxValue
        val customLabel = binding.editCustomLabel.text.toString().takeIf { it.isNotBlank() }
        
        val labelColor = try { Color.parseColor(binding.editLabelColor.text.toString()) } catch (e: Exception) { Color.LTGRAY }
        val valueColor = try { Color.parseColor(binding.editValueColor.text.toString()) } catch (e: Exception) { Color.WHITE }
        val needleColor = try { Color.parseColor(binding.editNeedleColor.text.toString()) } catch (e: Exception) { Color.RED }
        val scaleColor = try { Color.parseColor(binding.editScaleColor.text.toString()) } catch (e: Exception) { Color.WHITE }
        val fontSize = binding.editFontSize.text.toString().toIntOrNull() ?: 48

        val config = WidgetConfig.create(
            widgetId = widgetId,
            widgetType = widgetType,
            parameter = parameter,
            minValue = minValue,
            maxValue = maxValue,
            customLabel = customLabel,
            labelColor = labelColor,
            valueColor = valueColor,
            needleColor = needleColor,
            scaleColor = scaleColor,
            valueFontSize = fontSize
        )
        
        OBDWidgetProvider.saveWidgetConfig(this, widgetId, config)
        
        val appWidgetManager = AppWidgetManager.getInstance(this)
        val provider = OBDWidgetProvider()
        provider.onUpdate(this, appWidgetManager, intArrayOf(widgetId))
        
        val resultValue = Intent()
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId)
        setResult(Activity.RESULT_OK, resultValue)
        finish()
    }
}
