package com.prank.funnypranksounds.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
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.databinding.ActivityRecordAudioBinding;
import com.prank.funnypranksounds.utils.AudioUtils;
import com.prank.funnypranksounds.viewmodel.AudioViewModel;

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

public class RecordAudioActivity extends AppCompatActivity {

    private ActivityRecordAudioBinding binding;
    private boolean isStarted;
    private long time;
    private final Handler handler = new Handler();
    private MediaRecorder mediaRecorder;
    private File outputFile;

    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRecordAudioBinding.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() {
    }

    private void initEvent() {

        binding.voice.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(RecordAudioActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(RecordAudioActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION);
            } else {
                toggleRecording();
            }
        });

        binding.back.setOnClickListener(v -> onBackPressed());
    }

    private void toggleRecording() {
        if (isStarted) {
            stopRecording();
        } else {
            startRecording();
        }
        isStarted = !isStarted;
    }

    private final Runnable updateTimeTask = new Runnable() {
        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            long elapsedTime = currentTime - time;
            binding.time.setText(AudioUtils.formatTime(elapsedTime));
            handler.postDelayed(this, 1000);
        }
    };

    private void startRecording() {
        try {
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

            String fileName = "recording_" + System.currentTimeMillis() + ".m4a";
            outputFile = new File(getFilesDir(), fileName);
            mediaRecorder.setOutputFile(outputFile.getAbsolutePath());

            mediaRecorder.prepare();
            mediaRecorder.start();

            time = System.currentTimeMillis();
            handler.post(updateTimeTask);
            binding.animationView.playAnimation();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }

        handler.removeCallbacks(updateTimeTask);
        binding.animationView.cancelAnimation();
        binding.animationView.setFrame(0);
        binding.time.setText(R.string._00_00_00);

        Intent intent = new Intent(RecordAudioActivity.this, SaveAudioActivity.class);
        intent.putExtra("audioFilePath", outputFile.getAbsolutePath());
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isStarted) {
            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            }
            deleteRecordingFile();
        }
        finish();
    }

    private void deleteRecordingFile() {
        if (outputFile != null && outputFile.exists()) {
            boolean deleted = outputFile.delete();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}