package com.fun.wave.pranksounds.activity;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.fun.wave.pranksounds.R;
import com.fun.wave.pranksounds.base.BaseActivity;
import com.fun.wave.pranksounds.collection.CollectionFragment;
import com.fun.wave.pranksounds.databinding.OneActivityBinding;
import com.fun.wave.pranksounds.databinding.TabItemLayoutBinding;
import com.fun.wave.pranksounds.main.MainFragment;
import com.fun.wave.pranksounds.mine.MineFragment;
import com.fun.wave.pranksounds.mine.RecordingActivity;
import com.fun.wave.pranksounds.mine.SaveActivity;
import com.fun.wave.pranksounds.utils.Common;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OneActivity extends BaseActivity<OneActivityBinding> {


    private ActivityResultLauncher<String> audioPickerLauncher;

    private ActivityResultLauncher<String> requestRecordAudioLauncher;

    private ActivityResultLauncher<String[]> requestStorePermissionsLauncher;

    @Override
    protected void init() {
        initVp2();
        initImport();
        viewBind.importLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickTimer(0);
            }
        });
        viewBind.recordLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickTimer(1);
            }
        });

    }

    private void initImport() {
        requestRecordAudioLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        intentRecordAudio();
                    } else {
                        Toast.makeText(OneActivity.this, "Recording permission denied", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        requestStorePermissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                new ActivityResultCallback<Map<String, Boolean>>() {
                    @Override
                    public void onActivityResult(Map<String, Boolean> result) {
                        Boolean isGranted = true;
                        for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                            String permission = entry.getKey();
                            isGranted = entry.getValue();
                            if (!entry.getValue()) {
                                isGranted = false;
                            }

                        }
                        if (isGranted) {
                            importAudio();
                        } else {
                            Toast.makeText(OneActivity.this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
        audioPickerLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(),
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri uri) {
                        // Handle the returned Uri
                        if (uri != null) {
                            long duration = Common.getAudioDuration(OneActivity.this, uri);
                            Intent intent = new Intent(OneActivity.this, SaveActivity.class);
                            intent.putExtra(SaveActivity.KEY_Path, uri.toString());
//                            intent.putExtra(AcSave.KEY_Time, duration);
                            startActivity(intent);
                        }
                    }
                });
    }

    @Override
    protected OneActivityBinding initViewBinding() {
        return OneActivityBinding.inflate(getLayoutInflater());
    }

    private void intentRecordAudio() {
        Intent intent = new Intent(OneActivity.this, RecordingActivity.class);
        startActivity(intent);
    }

    private void initVp2() {
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(MainFragment.newInstance());
        fragmentList.add(CollectionFragment.newInstance());
        fragmentList.add(MineFragment.newInstance());
        viewBind.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        });

        viewBind.vp2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        new TabLayoutMediator(viewBind.bottomTab, viewBind.vp2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                TabItemLayoutBinding inflate = TabItemLayoutBinding.inflate(getLayoutInflater());
                tab.setCustomView(inflate.getRoot());
                switch (position) {
                    case 0 -> {
                        inflate.imageTab.setImageResource(R.drawable.tab_prank);
                        inflate.getRoot().animate()
                                .scaleX(1.7f)
                                .scaleY(1.7f)
                                .setDuration(200)
                                .start();
                    }
                    case 1 -> inflate.imageTab.setImageResource(R.drawable.tab_collection);
                    case 2 -> inflate.imageTab.setImageResource(R.drawable.tab_mine);
                }


            }
        }).attach();
        viewBind.bottomTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    customView.animate()
                            .scaleX(1.7f)
                            .scaleY(1.7f)
                            .setDuration(200)
                            .start();
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    View view = customView.findViewById(R.id.image_tab);
                    customView.animate()
                            .scaleX(1f)
                            .scaleY(1f)
                            .setDuration(200)
                            .start();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Common.REQUEST_READ_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                importAudio();
            } else {
                Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void importAudio() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        audioPickerLauncher.launch("audio/*");
    }

    public void onClickTimer(int type) {
        switch (type) {
            case 0:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    if (ContextCompat.checkSelfPermission(OneActivity.this, Common.permission_read_audio[0])
                            != PackageManager.PERMISSION_GRANTED) {
                        requestStorePermissionsLauncher.launch(Common.permission_read_audio);
                    } else {
                        importAudio();
                    }
                } else {
                    if (ContextCompat.checkSelfPermission(OneActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(OneActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {
                        requestStorePermissionsLauncher.launch(Common.permission_store);
                    } else {
                        importAudio();
                    }
                }
                break;
            case 1:
                checkAndRequestAudioPermission();
                break;
        }
    }

    private void checkAndRequestAudioPermission() {
        if (ContextCompat.checkSelfPermission(OneActivity.this, Common.permission_record_audio)
                != PackageManager.PERMISSION_GRANTED) {
            requestRecordAudioLauncher.launch(Common.permission_record_audio);
        } else {
            intentRecordAudio();
        }
    }
}