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 com.google.android.material.progressindicator.LinearProgressIndicator

import android.view.HapticFeedbackConstants
import android.transition.TransitionManager
import androidx.appcompat.app.AlertDialog
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

class HomeFragment : Fragment() {

    private val handler = Handler(Looper.getMainLooper())
    private lateinit var swipeRefresh: SwipeRefreshLayout
    private lateinit var pbRam: LinearProgressIndicator
    private lateinit var tvRamDetails: TextView
    private lateinit var pbStorage: LinearProgressIndicator
    private lateinit var tvStorageDetails: TextView
    private lateinit var tvSummary: TextView
    
    // Interactive Elements
    private lateinit var ramCard: View
    private lateinit var storageCard: View
    private lateinit var layoutRamMore: View
    private lateinit var layoutStorageMore: View
    private lateinit var ivExpandRam: android.widget.ImageView
    private lateinit var ivExpandStorage: android.widget.ImageView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        
        swipeRefresh = view.findViewById(R.id.swipeRefresh)
        pbRam = view.findViewById(R.id.pbRam)
        tvRamDetails = view.findViewById(R.id.tvRamDetails)
        pbStorage = view.findViewById(R.id.pbStorage)
        tvStorageDetails = view.findViewById(R.id.tvStorageDetails)
        tvSummary = view.findViewById(R.id.tvSummary)
        
        ramCard = view.findViewById(R.id.ramCard)
        storageCard = view.findViewById(R.id.storageCard)
        layoutRamMore = view.findViewById(R.id.layoutRamMore)
        layoutStorageMore = view.findViewById(R.id.layoutStorageMore)
        ivExpandRam = view.findViewById(R.id.ivExpandRam)
        ivExpandStorage = view.findViewById(R.id.ivExpandStorage)

        setupInteractions(view)
        updateStaticInfo()
        return view
    }

    private fun setupInteractions(view: View) {
        // Pull to Refresh
        swipeRefresh.setOnRefreshListener {
            view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
            updateStaticInfo()
            // Simulate refresh delay
            handler.postDelayed({ swipeRefresh.isRefreshing = false }, 1000)
        }

        // Expandable RAM Card
        ramCard.setOnClickListener {
            toggleExpansion(layoutRamMore, ivExpandRam)
        }

        // Expandable Storage Card
        storageCard.setOnClickListener {
            toggleExpansion(layoutStorageMore, ivExpandStorage)
        }

        // Detailed RAM Dialog
        pbRam.setOnClickListener {
            it.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
            showRamDetails()
        }

        // Detailed Storage Dialog
        pbStorage.setOnClickListener {
            it.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
            showStorageDetails()
        }

        view.findViewById<View>(R.id.btnCopySummary).setOnClickListener {
            it.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
            copyToClipboard("Device Summary", tvSummary.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 fun showRamDetails() {
        val ctx = context ?: return
        val activityManager = ctx.getSystemService(android.content.Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        val mi = android.app.ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(mi)
        
        val total = mi.totalMem / (1024 * 1024)
        val avail = mi.availMem / (1024 * 1024)
        val threshold = mi.threshold / (1024 * 1024)
        
        AlertDialog.Builder(ctx)
            .setTitle("Memory Breakdown")
            .setMessage("Total RAM: $total MB\nAvailable: $avail MB\nThreshold: $threshold MB\nLow Memory: ${mi.lowMemory}")
            .setPositiveButton("OK", null)
            .show()
    }

    private fun showStorageDetails() {
        val ctx = context ?: return
        AlertDialog.Builder(ctx)
            .setTitle("Storage Map")
            .setMessage("Internal Storage Details:\n${DeviceInfoProvider.getInternalStorageInfo()}\n\nNote: Includes System, Apps, and Media.")
            .setPositiveButton("OK", null)
            .show()
    }

    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()
    }

    private fun updateStaticInfo() {
        val storagePercent = DeviceInfoProvider.getStoragePercent()
        pbStorage.progress = storagePercent
        tvStorageDetails.text = DeviceInfoProvider.getInternalStorageInfo()
        
        tvSummary.text = "Device Model: ${DeviceInfoProvider.getModel()}\nAndroid: ${DeviceInfoProvider.getAndroidVersion()}"
    }

    private val liveUpdateRunnable = object : Runnable {
        override fun run() {
            context?.let { ctx ->
                val ramPercent = HardwareInfoProvider.getRamPercent(ctx)
                pbRam.progress = ramPercent
                tvRamDetails.text = DeviceInfoProvider.getRamInfo(ctx)
            }
            handler.postDelayed(this, 3000)
        }
    }

    override fun onResume() {
        super.onResume()
        handler.post(liveUpdateRunnable)
    }

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