package com.rugvedsarika.deviceinfo

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.fragment.app.Fragment

class SensorFragment : Fragment(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private var accelerometer: Sensor? = null
    private lateinit var sensorBall: View
    private lateinit var sensorContainer: FrameLayout
    private lateinit var tvSensorValues: TextView
    private lateinit var tvSensorsList: TextView

    private var lastShakeTime: Long = 0
    private var shakeThreshold = 12.0f

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_sensors, container, false)
        
        sensorBall = view.findViewById(R.id.sensorBall)
        sensorContainer = view.findViewById(R.id.sensorContainer)
        tvSensorValues = view.findViewById(R.id.tvSensorValues)
        tvSensorsList = view.findViewById(R.id.tvSensorsList)

        sensorManager = requireContext().getSystemService(Context.SENSOR_SERVICE) as SensorManager
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        
        val allSensors = sensorManager.getSensorList(Sensor.TYPE_ALL)
        val sensorNames = allSensors.joinToString("\n") { it.name }
        tvSensorsList.text = sensorNames

        view.findViewById<View>(R.id.btnCopySensors).setOnClickListener {
            it.performHapticFeedback(android.view.HapticFeedbackConstants.CONFIRM)
            copyToClipboard("Sensors List", sensorNames)
        }

        return view
    }

    private fun copyToClipboard(label: String, text: String) {
        val ctx = context ?: return
        val clipboard = ctx.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
        val clip = android.content.ClipData.newPlainText(label, text)
        clipboard.setPrimaryClip(clip)
        val v = view ?: return
        com.google.android.material.snackbar.Snackbar.make(v, "$label copied!", com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show()
    }

    override fun onResume() {
        super.onResume()
        accelerometer?.also { acc ->
            sensorManager.registerListener(this, acc, SensorManager.SENSOR_DELAY_UI)
        }
    }

    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]
            
            // Shake Detection
            val acceleration = Math.sqrt((x * x + y * y + z * z).toDouble()).toFloat() - SensorManager.GRAVITY_EARTH
            if (acceleration > shakeThreshold) {
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastShakeTime > 1000) {
                    lastShakeTime = currentTime
                    onShakeDetected()
                }
            }

            tvSensorValues.text = "X: %.1f, Y: %.1f".format(x, y)

            val containerWidth = sensorContainer.width.toFloat()
            val containerHeight = sensorContainer.height.toFloat()
            val ballWidth = sensorBall.width.toFloat()
            
            if (containerWidth > 0 && containerHeight > 0) {
                val centerX = (containerWidth - ballWidth) / 2
                val centerY = (containerHeight - ballWidth) / 2

                val targetX = (-x * 20).coerceIn(-centerX, centerX)
                val targetY = (y * 20).coerceIn(-centerY, centerY)

                // Haptic feedback if ball hits boundaries
                if (Math.abs(targetX) == centerX || Math.abs(targetY) == centerY) {
                    if (Math.abs(sensorBall.translationX) < centerX && Math.abs(sensorBall.translationY) < centerY) {
                        sensorBall.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
                    }
                }

                sensorBall.translationX = targetX
                sensorBall.translationY = targetY
            }
        }
    }

    private fun onShakeDetected() {
        val v = view ?: return
        sensorBall.performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS)
        com.google.android.material.snackbar.Snackbar.make(v, "Sensors Recalibrated ✨", com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show()
        // Randomize ball color for fun
        val colors = listOf(android.graphics.Color.RED, android.graphics.Color.BLUE, android.graphics.Color.GREEN, android.graphics.Color.MAGENTA, android.graphics.Color.CYAN)
        sensorBall.background?.setTint(colors.random())
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
}
