package com.rugvedsarika.voicereader.ui.saved

import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.rugvedsarika.voicereader.databinding.FragmentSavedAudioBinding
import java.io.File

class SavedAudioFragment : Fragment() {

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

    private lateinit var adapter: SavedAudioAdapter
    private var mediaPlayer: MediaPlayer? = null
    private var currentPlayingPath: String? = null

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

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

        adapter = SavedAudioAdapter(
            emptyList(),
            playingPath = currentPlayingPath,
            onPlay = { togglePlay(it) },
            onDelete = { deleteFile(it) },
            onDownload = { downloadFile(it) },
            onShare = { shareFile(it) }
        )
        binding.rvSavedAudio.adapter = adapter

        loadFiles()
    }

    private fun loadFiles() {
        val storageDir = context?.getExternalFilesDir(Environment.DIRECTORY_MUSIC)
        val files = storageDir?.listFiles { file -> file.extension == "wav" }?.toList() ?: emptyList()
        
        val sortedFiles = files.sortedByDescending { it.lastModified() }
        adapter.updateFiles(sortedFiles)

        binding.tvEmptyMsg.visibility = if (sortedFiles.isEmpty()) View.VISIBLE else View.GONE
        
        // Reset playing state if file no longer exists
        if (currentPlayingPath != null && sortedFiles.none { it.absolutePath == currentPlayingPath }) {
            stopPlayback()
        }
    }

    private fun togglePlay(file: File) {
        if (currentPlayingPath == file.absolutePath) {
            stopPlayback()
        } else {
            startPlayback(file)
        }
    }

    private fun startPlayback(file: File) {
        mediaPlayer?.release()
        currentPlayingPath = file.absolutePath
        adapter.updatePlayingPath(currentPlayingPath)

        mediaPlayer = MediaPlayer().apply {
            setDataSource(file.absolutePath)
            setOnCompletionListener {
                stopPlayback()
            }
            prepare()
            start()
        }
    }

    private fun stopPlayback() {
        mediaPlayer?.stop()
        mediaPlayer?.release()
        mediaPlayer = null
        currentPlayingPath = null
        adapter.updatePlayingPath(null)
    }

    private fun deleteFile(file: File) {
        if (file.absolutePath == currentPlayingPath) {
            stopPlayback()
        }
        if (file.delete()) {
            Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show()
            loadFiles()
        }
    }

    private fun shareFile(file: File) {
        val uri: Uri = FileProvider.getUriForFile(
            requireContext(),
            "${requireContext().packageName}.fileprovider",
            file
        )
        val intent = Intent(Intent.ACTION_SEND).apply {
            type = "audio/wav"
            putExtra(Intent.EXTRA_STREAM, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        startActivity(Intent.createChooser(intent, "Share Audio"))
    }

    private fun downloadFile(file: File) {
        try {
            val resolver = requireContext().contentResolver
            val contentValues = android.content.ContentValues().apply {
                put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, file.name)
                put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "audio/wav")
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
                }
            }

            val uri = resolver.insert(android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
            if (uri != null) {
                resolver.openOutputStream(uri)?.use { outputStream ->
                    file.inputStream().use { inputStream ->
                        inputStream.copyTo(outputStream)
                    }
                }
                Toast.makeText(context, getString(com.rugvedsarika.voicereader.R.string.msg_downloaded), Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, getString(com.rugvedsarika.voicereader.R.string.msg_error_download, "Could not create file"), Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(context, getString(com.rugvedsarika.voicereader.R.string.msg_error_download, e.message), Toast.LENGTH_SHORT).show()
        }
    }

    override fun onPause() {
        super.onPause()
        mediaPlayer?.stop()
        mediaPlayer?.release()
        mediaPlayer = null
    }

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