package com.fun.airhornprank.activity;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
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.view.View;
import android.widget.Toast;

import com.fun.airhornprank.R;
import com.fun.airhornprank.data.MyDataBase;
import com.fun.airhornprank.data.Mydata;
import com.fun.airhornprank.databinding.ActivitySaveBinding;
import com.fun.airhornprank.tool.Mytools;
import com.fun.airhornprank.tool.StaticValue;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class SaveActivity extends AppCompatActivity {
    private ActivitySaveBinding binding;
    private String path;
    private boolean isPlayerActive = false;
    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private Runnable timeUpdater;
    private long startTime;
    private long elapsedTime;
    private long audioDuration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySaveBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_save), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();
        initEvent();


    }

    private void togglePrank() throws IOException {
        if (!isPlayerActive) {
            startPrank();
        } else {
            stopPrank();
        }
    }

    private void stopPrank() {
        isPlayerActive = false;
        handler.removeCallbacks(timeUpdater);
        binding.savePlay.setBackgroundResource(R.drawable.pre_play);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void startPrank() throws IOException {
        isPlayerActive = true;
        binding.savePlay.setBackgroundResource(R.drawable.pre_pause);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build());
        mediaPlayer.setDataSource(path);
        mediaPlayer.setOnPreparedListener(mp -> {
            mediaPlayer.start();
            startTimer();
        });
        mediaPlayer.setOnCompletionListener(mp -> {
            handler.removeCallbacks(timeUpdater);
            binding.savePlay.setBackgroundResource(R.drawable.pre_play);
            isPlayerActive = false;
        });
        mediaPlayer.prepareAsync();
    }

    private void startTimer() {
        timeUpdater = new Runnable() {
            @SuppressLint("DefaultLocale")
            @Override
            public void run() {
                long currentTime = SystemClock.elapsedRealtime();
                elapsedTime = currentTime - startTime;
                int milliseconds = (int) (elapsedTime % 1000) / 10;
                int seconds = (int) (elapsedTime / 1000) % 60;
                int minutes = (int) (elapsedTime / (1000 * 60)) % 60;
                binding.saveTime.setText(String.format("%d : %02d : %02d", minutes, seconds, milliseconds));
                handler.postDelayed(this, 10);
            }
        };
        startTime = SystemClock.elapsedRealtime();
        handler.post(timeUpdater);
    }

    private void initEvent() {
        binding.saveBack.setOnClickListener(v -> finish());
        binding.savePlay.setOnClickListener(v -> {
            try {
                togglePrank();
            } catch (IOException e) {
                Log.e("SaveActivity", "Error toggling prank", e);
            }
        });
        binding.save.setOnClickListener(v -> {
            String name = binding.saveEdit.getText().toString().trim();
            if (!TextUtils.isEmpty(name)) {
                saveData(name);
                Toast.makeText(SaveActivity.this, getString(R.string.save_tips), Toast.LENGTH_SHORT).show();
                stopPrank();
                finish();
            } else {
                Toast.makeText(SaveActivity.this, getString(R.string.save_tip), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveData(String name) {
        File cacheDir = getCacheDir();
        File sourceFile = new File(path);
        File destinationFile = new File(cacheDir, name + ".mp3");

        if (sourceFile.renameTo(destinationFile)) {
            Mydata mydata = new Mydata();
            mydata.setCategoryname("custom");
            mydata.setLike(false);
            mydata.setTitle(name);
            mydata.setMp3Url(destinationFile.getAbsolutePath());
            mydata.setPreUrl("custom_url");
            mydata.setCategoryUrl("custom_url");
            mydata.setTime(audioDuration);

            Mytools.runIO(() -> MyDataBase.getInstance().likeDAO().insertCustom(mydata));
        } else {
            Log.e("SaveActivity", "Failed to rename file");
        }
    }


    private String readFileFromUri(Context context, Uri uri) {
        ContentResolver contentResolver = context.getContentResolver();
        try (InputStream inputStream = contentResolver.openInputStream(uri);
             FileOutputStream outputStream = new FileOutputStream(new File(getCacheDir(), "temp_audio_file.mp3"))) {

            if (inputStream == null) {
                Log.e("SaveActivity", "Input stream is null");
                return null;
            }

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            return new File(getCacheDir(), "temp_audio_file.mp3").getAbsolutePath();
        } catch (IOException e) {
            Log.e("SaveActivity", "Error reading file from URI", e);
            return null;
        }
    }

    private void initData() {
        Intent intent = getIntent();
        audioDuration = intent.getLongExtra(StaticValue.KEY_Time, 0);
        int importFlag = intent.getIntExtra(StaticValue.KEY_import, 0);

        if (importFlag == 1) {
            path = intent.getStringExtra(StaticValue.KEY_Path);
        } else {
            String uriPath = intent.getStringExtra(StaticValue.KEY_Path);
            Uri uri = Uri.parse(uriPath);
            path = readFileFromUri(this, uri);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPrank();
    }
}
