package com.jrz.nfcapp.ui

import android.app.PendingIntent
import android.content.Intent
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.jrz.nfcapp.R
import com.jrz.nfcapp.databinding.ActivityMainBinding
import com.jrz.nfcapp.ui.clone.CloneFragment
import com.jrz.nfcapp.ui.hce.HceFragment
import com.jrz.nfcapp.ui.read.ReadFragment
import com.jrz.nfcapp.ui.write.WriteFragment

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var nfcAdapter: NfcAdapter? = null
    private var pendingIntent: PendingIntent? = null

    private lateinit var readFragment: ReadFragment
    private lateinit var writeFragment: WriteFragment
    private lateinit var cloneFragment: CloneFragment
    private lateinit var hceFragment: HceFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        // Edge-to-edge: content draws behind status & nav bar
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Apply insets: AppBarLayout handles top via fitsSystemWindows,
        // ViewPager gets bottom padding for the navigation bar
        ViewCompat.setOnApplyWindowInsetsListener(binding.viewPager) { view, insets ->
            val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            view.updatePadding(bottom = bars.bottom)
            insets
        }

        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (nfcAdapter == null) {
            Toast.makeText(this, getString(R.string.nfc_not_supported), Toast.LENGTH_LONG).show()
            updateNfcBadge(supported = false)
        } else {
            updateNfcBadge(supported = true)
        }

        val intent = Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        pendingIntent = PendingIntent.getActivity(
            this, 0, intent,
            PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        setupViewPager()

        if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
            onNewIntent(intent)
        }
    }

    private fun updateNfcBadge(supported: Boolean) {
        if (!supported) {
            binding.tvNfcStatus.text = "KEIN NFC"
            binding.nfcStatusDot.setBackgroundResource(R.drawable.dot_inactive)
        }
    }

    private fun setupViewPager() {
        readFragment = ReadFragment()
        writeFragment = WriteFragment()
        cloneFragment = CloneFragment()
        hceFragment = HceFragment()

        val fragments = listOf(readFragment, writeFragment, cloneFragment, hceFragment)
        val titles = listOf(
            getString(R.string.tab_read),
            getString(R.string.tab_write),
            getString(R.string.tab_clone),
            getString(R.string.tab_hce)
        )

        binding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = fragments.size
            override fun createFragment(position: Int) = fragments[position]
        }

        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.text = titles[position]
        }.attach()
    }

    override fun onResume() {
        super.onResume()
        val adapter = nfcAdapter ?: return
        if (!adapter.isEnabled) {
            Toast.makeText(this, getString(R.string.nfc_disabled), Toast.LENGTH_LONG).show()
            binding.tvNfcStatus.text = "AUS"
            binding.nfcStatusDot.setBackgroundResource(R.drawable.dot_inactive)
            return
        }
        binding.tvNfcStatus.text = "NFC"
        binding.nfcStatusDot.setBackgroundResource(R.drawable.dot_active)
        adapter.enableForegroundDispatch(this, pendingIntent, null, null)
    }

    override fun onPause() {
        super.onPause()
        nfcAdapter?.disableForegroundDispatch(this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG) ?: return
        when (binding.viewPager.currentItem) {
            0 -> readFragment.onTagScanned(tag)
            1 -> writeFragment.onTagScanned(tag)
            2 -> cloneFragment.onTagScanned(tag)
        }
    }
}
