package com.rugvedsarika.deviceinfo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import android.view.HapticFeedbackConstants
import android.transition.TransitionManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

class BatteryFragment : Fragment() {

    private lateinit var swipeRefresh: SwipeRefreshLayout
    private lateinit var batteryCard: View
    private lateinit var layoutBatteryMore: View
    private lateinit var ivExpandBattery: android.widget.ImageView

    private val handler = Handler(Looper.getMainLooper())
    private lateinit var tvBatteryInfo: TextView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_battery, container, false)
        tvBatteryInfo = view.findViewById(R.id.tvBatteryInfo)

        swipeRefresh = view.findViewById(R.id.swipeRefresh)
        batteryCard = view.findViewById(R.id.batteryCard)
        layoutBatteryMore = view.findViewById(R.id.layoutBatteryMore)
        ivExpandBattery = view.findViewById(R.id.ivExpandBattery)

        setupInteractions(view)

        view.findViewById<View>(R.id.btnBatterySettings).setOnClickListener {
            it.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
            try {
                startActivity(android.content.Intent(android.content.Intent.ACTION_POWER_USAGE_SUMMARY))
            } catch (e: Exception) {
                startActivity(android.content.Intent(android.provider.Settings.ACTION_BATTERY_SAVER_SETTINGS))
            }
        }

        return view
    }

    private fun setupInteractions(view: View) {
        swipeRefresh.setOnRefreshListener {
            view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
            // Refresh is already handled by the background runnable, but let's reset it
            view.postDelayed({ swipeRefresh.isRefreshing = false }, 1000)
        }

        batteryCard.setOnClickListener {
            toggleExpansion(layoutBatteryMore, ivExpandBattery)
        }

        view.findViewById<View>(R.id.btnCopyBattery).setOnClickListener {
            it.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
            copyToClipboard("Battery Info", tvBatteryInfo.text.toString())
        }
    }

    private fun toggleExpansion(layout: View, icon: android.widget.ImageView) {
        val container = layout.parent.parent as ViewGroup
        TransitionManager.beginDelayedTransition(container)
        if (layout.visibility == View.GONE) {
            layout.visibility = View.VISIBLE
            icon.animate().rotation(180f).start()
        } else {
            layout.visibility = View.GONE
            icon.animate().rotation(0f).start()
        }
    }

    private val updateRunnable = object : Runnable {
        override fun run() {
            context?.let { ctx ->
                val battery = HardwareInfoProvider.getBatteryInfo(ctx)
                tvBatteryInfo.text = """
                    Level: ${battery["Level"]}
                    Health: ${battery["Health"]}
                    Temperature: ${battery["Temperature"]}
                    Technology: ${battery["Technology"]}
                """.trimIndent()
            }
            handler.postDelayed(this, 2000)
        }
    }

    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()
        handler.post(updateRunnable)
    }

    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(updateRunnable)
    }
}
