package com.prank.funnypranksounds.ui.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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

import com.prank.funnypranksounds.R;
import com.prank.funnypranksounds.data.local.database.AppDatabase;
import com.prank.funnypranksounds.data.local.entity.AudioData;
import com.prank.funnypranksounds.databinding.ActivitySaveAudioBinding;
import com.prank.funnypranksounds.utils.AudioUtils;
import com.prank.funnypranksounds.viewmodel.AudioViewModel;

import java.io.File;
import java.io.IOException;

public class SaveAudioActivity extends AppCompatActivity {

    private ActivitySaveAudioBinding binding;
    private AudioViewModel audioViewModel;
    private String audioFilePath;
    private String inputText;
    private MediaPlayer mediaPlayer;
    private boolean isPlaying;
    private int duration;
    private boolean isSaved;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySaveAudioBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (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 initData() {
        audioFilePath = getIntent().getStringExtra("audioFilePath");
        if (audioFilePath == null) {
            Toast.makeText(this, "The audio file path is invalid", Toast.LENGTH_SHORT).show();
            return;
        }

        File audioFile = new File(audioFilePath);
        if (!audioFile.exists()) {
            Toast.makeText(this, "Audio file does not exist", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        audioViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication()))
                .get(AudioViewModel.class);

    }

    private void initEvent() {
        binding.back.setOnClickListener(v -> handleBackPressed());
        binding.play.setOnClickListener(v -> playOrPauseAudio());

        binding.save.setOnClickListener(v -> {
            inputText = binding.editText.getText().toString();
            if (inputText.trim().isEmpty()) {
                Toast.makeText(getApplicationContext(), "The name cannot be empty", Toast.LENGTH_SHORT).show();
                return;
            }

            audioViewModel.insert(new AudioData(inputText, audioFilePath, inputText, audioFilePath, "", false, true));

            isSaved = true;

            Intent intent = new Intent(SaveAudioActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            finish();
        });

        displayAudioDuration();

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                handleBackPressed();
            }
        });
    }

    private void displayAudioDuration() {
        if (audioFilePath != null) {
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(audioFilePath);
                mediaPlayer.prepare();

                duration = mediaPlayer.getDuration();
                binding.time.setText(AudioUtils.formatTime(duration));

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "Unable to load audio", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "The audio file path is invalid", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleBackPressed() {
        deleteRecordingFile();
        finish();
    }

    private void deleteRecordingFile() {
        File file = new File(audioFilePath);
        if (file.exists()) {
            boolean deleted = file.delete();
        }
    }

    private void playOrPauseAudio() {
        if (isPlaying) {
            mediaPlayer.pause();
            binding.play.setImageResource(R.drawable.play);
            isPlaying = false;
        } else {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(audioFilePath);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "Unable to play audio", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            mediaPlayer.start();
            binding.play.setImageResource(R.drawable.pause);
            isPlaying = true;

            mediaPlayer.setOnCompletionListener(mp -> {
                Toast.makeText(this, "Play completed", Toast.LENGTH_SHORT).show();
                binding.play.setImageResource(R.drawable.play);
                isPlaying = false;
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (isPlaying) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (!isSaved) {
            deleteRecordingFile();
        }
        binding = null;
    }
}