package com.sound.prankparty.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;

import com.sound.prankparty.R;
import com.sound.prankparty.Room.AppDatabase;
import com.sound.prankparty.Room.SaveSounds;
import com.sound.prankparty.Room.SaveSoundsDao;
import com.sound.prankparty.databinding.ActivitySaveRecordBinding;

import java.io.File;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SaveRecordActivity extends AppCompatActivity {

    private ActivitySaveRecordBinding binding;
    private String audioFilePath;
    private String inputText;
    private MediaPlayer mediaPlayer;
    private String datePart;
    private String timePart;
    private boolean isPlaying = false;
    private AppDatabase appDatabase;
    private SaveSoundsDao saveSoundsDao;
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivitySaveRecordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 获取传递过来的录音文件路径
        audioFilePath = getIntent().getStringExtra("audioFilePath");
        if (audioFilePath == null) {
            Toast.makeText(this, "音频文件路径无效", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d("SaveRecordActivity", audioFilePath);

        // 初始化数据库和 DAO
        appDatabase = AppDatabase.getDatabase(this);
        saveSoundsDao = appDatabase.saveSoundsDao();


        // 创建一个 SpannableString 并设置它的大小
        SpannableString hint = new SpannableString(getString(R.string.give_name));
        hint.setSpan(new AbsoluteSizeSpan(15, true), 0, hint.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置字体大小为 20sp

        binding.saveRecordName.setHint(hint);

        // 设置焦点变化监听器
        binding.saveRecordName.setOnFocusChangeListener((v, hasFocus) -> binding.saveRecordName.setCursorVisible(hasFocus));

        binding.saveRecordBack.setOnClickListener(v -> handleBackPressed());

        // 添加 OnBackPressedCallback 来处理返回操作
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 调用相同的处理逻辑
                handleBackPressed();
            }
        });

        // 处理全局点击事件
        binding.main.setOnClickListener(v -> {
            if (v instanceof ViewGroup) {
                clearFocusFromAllChildren((ViewGroup) v);
            } else {
                clearFocus();
            }
            inputText = binding.saveRecordName.getText().toString();
            Log.d("lux231", "13" + inputText);
        });

        // 显示音频文件的时长
        displayAudioDuration();

        binding.saveRecordPlay.setOnClickListener(v -> playOrPauseAudio());

        binding.saveRecordSave.setOnClickListener(v -> {
            inputText = binding.saveRecordName.getText().toString();
            //检测是否输入为空字符串
            if (inputText.trim().isEmpty()) {
                Toast.makeText(getApplicationContext(), "名称不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            formatDateTime();

            new Thread(() -> {
                saveSoundsDao.insertSound(new SaveSounds(inputText, audioFilePath, datePart, timePart, formatTime(duration)));

                runOnUiThread(() -> {
                    Intent intent = new Intent(SaveRecordActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    finish();
                });
            }).start();
        });
    }

    public void handleBackPressed() {
        // 删除录音文件
        deleteRecordingFile();
        finish();
    }

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

    private void clearFocusFromAllChildren(ViewGroup parent) {
        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                clearFocusFromAllChildren((ViewGroup) child);
            } else {
                child.clearFocus();
            }
        }
    }

    private void clearFocus() {
        binding.saveRecordName.clearFocus();
    }

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

                duration = mediaPlayer.getDuration();
                binding.saveRecordTime.setText(formatTime(duration));

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "无法加载音频", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "音频文件路径无效", Toast.LENGTH_SHORT).show();
        }
    }

    private void playOrPauseAudio() {
        if (isPlaying) {
            mediaPlayer.pause();
            binding.saveRecordPlay.setImageResource(R.drawable.playback);  // 更新按钮为播放图标
            isPlaying = false;
        } else {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(audioFilePath);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "无法播放音频", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            mediaPlayer.start();
            binding.saveRecordPlay.setImageResource(R.drawable.pause);  // 更新按钮为暂停图标
            isPlaying = true;

            mediaPlayer.setOnCompletionListener(mp -> {
                Toast.makeText(this, "播放完成", Toast.LENGTH_SHORT).show();
                binding.saveRecordPlay.setImageResource(R.drawable.playback);  // 恢复播放图标
                isPlaying = false;
            });
        }
    }

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

    @SuppressLint("DefaultLocale")
    private String formatTime(int duration) {
        int seconds = (duration / 1000) % 60;
        int minutes = (duration / (1000 * 60)) % 60;
        int hours = (duration / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    private void formatDateTime() {
        Date currentDate = new Date();

        // 自定义DateFormatSymbols以使用小写的am和pm
        DateFormatSymbols dfs = new DateFormatSymbols(Locale.ENGLISH);
        dfs.setAmPmStrings(new String[]{"am", "pm"});
        // 新的格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
        SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mma", Locale.ENGLISH);
        timeFormat.setDateFormatSymbols(dfs);

        // 赋值给原有变量名
        datePart = dateFormat.format(currentDate);
        timePart = timeFormat.format(currentDate);
    }
}
