package com.prank.happypranksounds.ui.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
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.happypranksounds.R;
import com.prank.happypranksounds.data.entity.HappyData;
import com.prank.happypranksounds.databinding.ActivitySaveBinding;
import com.prank.happypranksounds.topon.AdManager;
import com.prank.happypranksounds.topon.onActionListener;
import com.prank.happypranksounds.ui.viewmodel.HappyViewModel;
import com.prank.happypranksounds.util.HappySoundUtil;

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

public class SaveActivity extends AppCompatActivity {

    private ActivitySaveBinding binding;
    private HappyViewModel happyViewModel;
    private String soundPath;
    private String inputText;
    private MediaPlayer mediaPlayer;
    private boolean isPlaying;
    private boolean isSaved;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySaveBinding.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() {
        soundPath = getIntent().getStringExtra("soundPath");
        if (soundPath == null) {
            Toast.makeText(this, "The audio file path is invalid", Toast.LENGTH_SHORT).show();
            return;
        }

        AdManager.loadAllAd();

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

        happyViewModel = new ViewModelProvider(this).get(HappyViewModel.class);
    }

    private void initEvent() {
        setupBackButton();
        setupPlayButton();
        setupSaveButton();
        displayAudioDuration();
        handleBackPressOnPhysicalButton();
    }

    private void setupBackButton() {
        binding.back.setOnClickListener(v -> {
            AdManager.showTopOn(this, new onActionListener() {
                @Override
                public void onAction() {
                    handleBackPressed();
                }
            });
        });
    }

    private void setupPlayButton() {
        binding.play.setOnClickListener(v -> playOrPauseAudio());
    }

    private void setupSaveButton() {
        binding.save.setOnClickListener(v -> {
            inputText = binding.editText.getText().toString().trim();

            if (inputText.isEmpty()) {
                showToast(R.string.name_is_empty);
                return;
            }

            saveData();
            navigateToMainActivity();
        });
    }

    private void saveData() {
        HappyData happyData = new HappyData(inputText, soundPath, inputText, soundPath, "", false, true);
        happyViewModel.insert(happyData);
        isSaved = true;
    }

    private void navigateToMainActivity() {
        Intent intent = new Intent(SaveActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    private void showToast(int resId) {
        Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_SHORT).show();
    }

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

    private void displayAudioDuration() {
        if (soundPath != null) {
            initializeMediaPlayer(true);
        } else {
            Toast.makeText(this, "The audio file path is invalid", Toast.LENGTH_SHORT).show();
        }
    }

    private void playOrPauseAudio() {
        if (isPlaying) {
            mediaPlayer.pause();
            binding.play.setImageResource(R.drawable.play);
            isPlaying = false;
        } else {
            if (mediaPlayer == null) {
                initializeMediaPlayer(false);
            } else {
                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;
            });
        }
    }

    private void initializeMediaPlayer(boolean forDuration) {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }

        try {
            mediaPlayer.setDataSource(soundPath);
            mediaPlayer.prepareAsync();

            if (forDuration) {
                mediaPlayer.setOnPreparedListener(mp -> {
                    int duration = mediaPlayer.getDuration();
                    binding.time.setText(HappySoundUtil.formatTime(duration));
                });
            } else {
                mediaPlayer.setOnPreparedListener(mp -> {
                    mediaPlayer.start();
                    binding.play.setImageResource(R.drawable.pause);
                    isPlaying = true;
                });
            }

            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Toast.makeText(this, "Unable to play audio", Toast.LENGTH_SHORT).show();
                return true;
            });

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Unable to load audio", Toast.LENGTH_SHORT).show();
        }
    }

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

    private void deleteFile() {
        if (soundPath == null) {
            return;
        }

        File file = new File(soundPath);
        if (file.exists()) {
            boolean deleted = file.delete();
            if (!deleted) {
                Toast.makeText(this, "Failed to delete audio file", Toast.LENGTH_SHORT).show();
            }
        }
    }

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