package com.prank.happypranksounds.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 android.os.SystemClock;
import android.widget.Toast;

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 com.prank.happypranksounds.R;
import com.prank.happypranksounds.databinding.ActivityRecordBinding;
import com.prank.happypranksounds.topon.AdManager;
import com.prank.happypranksounds.topon.onActionListener;
import com.prank.happypranksounds.util.HappySoundUtil;

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

public class RecordActivity extends AppCompatActivity {

    private ActivityRecordBinding 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;

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

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

        AdManager.loadAllAd();

        initEvent();
    }

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

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

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

    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.animation.playAnimation();

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Recording failed", Toast.LENGTH_SHORT).show();
        }
    }

    private void stopRecording() {
        if (mediaRecorder != null) {
            try {
                mediaRecorder.stop();
            } catch (RuntimeException e) {
                e.printStackTrace();
                Toast.makeText(this, "Recording failed", Toast.LENGTH_SHORT).show();
            } finally {
                mediaRecorder.release();
                mediaRecorder = null;
            }
        }

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

        Intent intent = new Intent(RecordActivity.this, SaveActivity.class);
        intent.putExtra("soundPath", outputFile.getAbsolutePath());
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        if (isStarted) {
            stopRecordingAndDeleteFile();
        }
        super.onBackPressed();
    }

    private void stopRecordingAndDeleteFile() {
        if (mediaRecorder != null) {
            try {
                mediaRecorder.stop();
            } catch (RuntimeException e) {
                e.printStackTrace();
                Toast.makeText(this, "Recording stopped unexpectedly", Toast.LENGTH_SHORT).show();
            } finally {
                mediaRecorder.release();
                mediaRecorder = null;
            }
        }

        deleteFile();
    }

    private void deleteFile() {
        if (outputFile != null && outputFile.exists()) {
            boolean deleted = outputFile.delete();
            if (!deleted) {
                Toast.makeText(this, "Failed to delete recording file", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaRecorder != null) {
            mediaRecorder.release();
            mediaRecorder = null;
        }
        handler.removeCallbacks(updateTimeTask);
        binding = null;
    }
}