package com.soundapp.soundgags.ui

import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.soundapp.soundgags.R
import com.soundapp.soundgags.datame.Reflection
import com.soundapp.soundgags.datame.MainViewModel
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import androidx.core.net.toUri
import com.ad.tradpluslibrary.TPAdManager.showTPAD
import com.soundapp.soundgags.databinding.ActivityVoiceRecorderBinding
import com.soundapp.soundgags.setting.TopBarUtils

class VoiceRecorderActivity : AppCompatActivity() {
    private lateinit var binding: ActivityVoiceRecorderBinding
    private var path: String? = null

    private var mediaPlayer: MediaPlayer? = null
    private val handler = Handler()
    private var timeUpdater: Runnable? = null
    private var startTime: Long = 0
    private var elapsedTime: Long = 0
    private lateinit var viewModel: MainViewModel
    private var audioDuration: Long = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TopBarUtils.setStatusBar(this.window)
        TopBarUtils.setLightStatusBar(this.window, true)
        binding = ActivityVoiceRecorderBinding.inflate(layoutInflater)
        setContentView(binding.root)
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        binding.audioTime.setText(R.string.time_init)
        initData()
        initEvent()

    }

    @Throws(IOException::class)
    private fun togglePrank() {
        if (binding.btnPlay.isSelected) {
            initMediaPlayer()
        } else {
            stopPlay()
        }
    }

    private fun stopPlay() {
        if (timeUpdater != null) {
            handler.removeCallbacks(timeUpdater!!)
        }
        if (mediaPlayer != null) {
            mediaPlayer!!.release()
            mediaPlayer = null
        }
    }

    private fun initMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = MediaPlayer()
            mediaPlayer!!.setAudioAttributes(
                AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .build()
            )
            try {
                mediaPlayer!!.setDataSource(path)
            } catch (_: Exception) {
            }
            mediaPlayer!!.setOnPreparedListener { mp: MediaPlayer? ->
                mediaPlayer!!.start()
                beginTimer()
            }
            mediaPlayer!!.setOnCompletionListener { mp: MediaPlayer? ->
                binding.btnPlay.isSelected = false
                handler.removeCallbacks(timeUpdater!!)
            }
            mediaPlayer!!.prepareAsync()
        } else {
            mediaPlayer!!.start()
            beginTimer()
        }
    }


    private fun beginTimer() {
        if (timeUpdater == null) {
            timeUpdater = object : Runnable {
                @SuppressLint("DefaultLocale")
                override fun run() {
                    if (mediaPlayer != null && mediaPlayer!!.isPlaying) {
                        val currentTime = SystemClock.elapsedRealtime()
                        elapsedTime = currentTime - startTime
                        val milliseconds = (elapsedTime % 1000).toInt() / 10
                        val seconds = (elapsedTime / 1000).toInt() % 60
                        val minutes = (elapsedTime / (1000 * 60)).toInt() % 60
                        binding.audioTime.text =
                            String.format(
                                "%02d : %02d : %02d",
                                minutes,
                                seconds,
                                milliseconds
                            )
                        handler.postDelayed(this, 10)
                    }
                }
            }
        }
        startTime = SystemClock.elapsedRealtime()
        handler.post(timeUpdater!!)
    }

    private fun initEvent() {
        binding.back.setOnClickListener { finish() }
        binding.audioTimeLayout.setOnClickListener {
            showTPAD(this){
                binding.btnPlay.isSelected = !binding.btnPlay.isSelected
            }
            try {
                togglePrank()
            } catch (e: IOException) {
                Log.e("SaveActivity", "Error toggling prank", e)
            }
        }

        binding.save.setOnClickListener {
            showTPAD(this){}
            val name = binding.saveEdit.text.toString().trim()
            viewModel.checkSaveStatus(name, callback = { isSave ->
                runOnUiThread {
                    // 1. 先检查Activity是否即将销毁，避免在已销毁的Activity上操作
                    if (isFinishing || isDestroyed) {
                        return@runOnUiThread
                    }
                    if (TextUtils.isEmpty(name)) {
                        Toast.makeText(
                            this@VoiceRecorderActivity,
                            getString(R.string.save_tip), // 空名称提示
                            Toast.LENGTH_SHORT
                        ).show()
                        return@runOnUiThread
                    }

                    if (isSave) {
                        binding.saveEdit.setText("")
                        Toast.makeText(
                            this@VoiceRecorderActivity, // 使用显式的 this@ActivityName
                            getString(R.string.name_hint), // 名称已存在提示
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        saveData(name)
                        Toast.makeText(
                            this@VoiceRecorderActivity,
                            getString(R.string.save_tips), // 保存成功提示
                            Toast.LENGTH_SHORT
                        ).show()
                        finish()
                    }
                }
            })
        }

    }

    private fun saveData(name: String) {
        val cacheDir = cacheDir
        val sourceFile = File(path)
        val destinationFile = File(cacheDir, "$name.mp3")

        if (sourceFile.renameTo(destinationFile)) {
            val mydata = Reflection()
            mydata.isLike = false
            mydata.name = name
            mydata.isCustomization = true
            mydata.audioUrl = destinationFile.absolutePath
            viewModel.insertItem(mydata)
        } else {
            Log.e("SaveActivity", "Failed to rename file")
        }
    }


    private fun readFileFromUri(context: Context, uri: Uri): String? {
        val contentResolver = context.contentResolver
        try {
            contentResolver.openInputStream(uri).use { inputStream ->
                FileOutputStream(
                    File(
                        cacheDir, "temp_audio_file.mp3"
                    )
                ).use { outputStream ->
                    if (inputStream == null) {
                        Log.e("SaveActivity", "Input stream is null")
                        return null
                    }
                    val buffer = ByteArray(1024)
                    var bytesRead: Int
                    while ((inputStream.read(buffer).also { bytesRead = it }) != -1) {
                        outputStream.write(buffer, 0, bytesRead)
                    }
                    return File(cacheDir, "temp_audio_file.mp3").absolutePath
                }
            }
        } catch (e: IOException) {
            Log.e("SaveActivity", "Error reading file from URI", e)
            return null
        }
    }

    private fun initData() {
        val intent = intent
        audioDuration = intent.getLongExtra(KEY_Time, 0)
        val importFlag = intent.getIntExtra(KEY_import, 0)

        if (importFlag == 1) {
            path = intent.getStringExtra(KEY_Path)
            Log.e("zzj", "save path is$path")
        } else {
            val uriPath = intent.getStringExtra(KEY_Path)
            val uri = uriPath!!.toUri()
            path = readFileFromUri(this, uri)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        stopPlay()
    }

    companion object {
        var KEY_Time: String = "KEY_time"
        var KEY_Path: String = "KEY_path"
        var KEY_import: String = "flag"
    }
}