package com.jrz.nfcapp.ui.hce

import android.content.ComponentName
import android.content.Intent
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.cardemulation.CardEmulation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.google.android.material.snackbar.Snackbar
import com.jrz.nfcapp.R
import com.jrz.nfcapp.databinding.FragmentHceBinding
import com.jrz.nfcapp.service.HceService

class HceFragment : Fragment() {

    private var _binding: FragmentHceBinding? = null
    private val binding get() = _binding!!

    private var isActive = false
    private val apduLogLines = ArrayDeque<String>(200)

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentHceBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.btnEnableHce.setOnClickListener { enableHce() }
        binding.btnDisableHce.setOnClickListener { disableHce() }
        binding.btnClearLog.setOnClickListener {
            apduLogLines.clear()
            binding.tvApduLog.text = "Kein APDU-Verkehr…"
        }

        // Register log callback
        HceService.apduLogCallback = { line ->
            requireActivity().runOnUiThread { appendLog(line) }
        }
    }

    private fun enableHce() {
        val aid = binding.etAid.text?.toString()?.trim()?.replace(" ", "")?.uppercase() ?: ""
        val payloadText = binding.etPayload.text?.toString()?.trim() ?: ""

        if (aid.isEmpty()) {
            Snackbar.make(binding.root, "Bitte AID eingeben", Snackbar.LENGTH_SHORT).show()
            return
        }
        if (aid.length % 2 != 0 || aid.length < 10 || aid.length > 32) {
            Snackbar.make(binding.root, "AID muss 5-16 Hex-Bytes sein", Snackbar.LENGTH_LONG).show()
            return
        }

        // Build NDEF payload
        HceService.ndefPayload = buildNdefPayload(payloadText)

        isActive = true
        updateUi()
        appendLog("=== HCE aktiviert, AID: $aid ===")
        Snackbar.make(binding.root, "HCE aktiv. Halte das Telefon an ein Lesegerät.", Snackbar.LENGTH_LONG).show()
    }

    private fun disableHce() {
        isActive = false
        updateUi()
        appendLog("=== HCE deaktiviert ===")
    }

    private fun updateUi() {
        binding.hceStatusDot.setBackgroundResource(
            if (isActive) R.drawable.dot_active else R.drawable.dot_inactive
        )
        binding.tvHceStatus.text = getString(
            if (isActive) R.string.hce_status_active else R.string.hce_status_inactive
        )
        binding.btnEnableHce.isEnabled = !isActive
        binding.btnDisableHce.isEnabled = isActive
        binding.etAid.isEnabled = !isActive
        binding.etPayload.isEnabled = !isActive
    }

    private fun appendLog(line: String) {
        apduLogLines.addLast(line)
        if (apduLogLines.size > 100) apduLogLines.removeFirst()
        binding.tvApduLog.text = apduLogLines.joinToString("\n")
    }

    private fun buildNdefPayload(text: String): ByteArray {
        if (text.isEmpty()) return HceService.buildDefaultNdefPayload()

        val lang = "de"
        val langBytes = lang.toByteArray()
        val textBytes = text.toByteArray(Charsets.UTF_8)
        val recordPayload = ByteArray(1 + langBytes.size + textBytes.size)
        recordPayload[0] = langBytes.size.toByte()
        langBytes.copyInto(recordPayload, 1)
        textBytes.copyInto(recordPayload, 1 + langBytes.size)

        val typeBytes = byteArrayOf(0x54)
        val ndefRecord = byteArrayOf(
            0xD1.toByte(),
            typeBytes.size.toByte(),
            recordPayload.size.toByte()
        ) + typeBytes + recordPayload

        return byteArrayOf(0x00, ndefRecord.size.toByte()) + ndefRecord
    }

    override fun onDestroyView() {
        HceService.apduLogCallback = null
        super.onDestroyView()
        _binding = null
    }
}
