package com.prank.happypranksounds.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.prank.happypranksounds.R;
import com.prank.happypranksounds.callback.HappyCallback;
import com.prank.happypranksounds.data.entity.HappyData;
import com.prank.happypranksounds.data.repository.HappyRepository;
import com.prank.happypranksounds.databinding.FragmentSoundBinding;
import com.prank.happypranksounds.topon.AdManager;
import com.prank.happypranksounds.topon.onActionListener;
import com.prank.happypranksounds.ui.activity.RecordActivity;
import com.prank.happypranksounds.ui.adapter.SoundAdapter;
import com.prank.happypranksounds.ui.viewmodel.HappyViewModel;
import com.prank.happypranksounds.util.HappySoundUtil;

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

public class SoundFragment extends Fragment implements HappyCallback.OnItemSwipeListener {

    private FragmentSoundBinding binding;
    private SoundAdapter adapter;
    private HappyViewModel happyViewModel;
    private Uri audioUri;
    private String fileName;
    private List<HappyData> happyDataList = new ArrayList<>();
    private static final int REQUEST_CODE_READ_MEDIA_AUDIO = 1001;
    private static final int REQUEST_CODE_PICK_AUDIO = 1002;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentSoundBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        happyViewModel = new ViewModelProvider(this).get(HappyViewModel.class);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
        adapter = new SoundAdapter(happyDataList, happyViewModel, requireContext(), 1);
        binding.recyclerView.setAdapter(adapter);

        HappyCallback callback = new HappyCallback(this);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(binding.recyclerView);
    }

    private void initEvent() {
        binding.add.setOnClickListener(v -> {
            AdManager.showTopOn(getActivity(), new onActionListener() {
                @Override
                public void onAction() {
                    showCustomBottomSheetDialog();
                }
            });
        });
        loadExt();
    }

    private void loadExt() {
        happyViewModel.getExternal().observe(getViewLifecycleOwner(), dataList -> {
            updateUIForEmptyData(dataList);
            happyDataList = dataList;
            adapter.updateData(dataList);
        });
    }

    private void updateUIForEmptyData(List<HappyData> dataList) {
        if (dataList.isEmpty()) {
            binding.soundText.setVisibility(View.VISIBLE);
        } else {
            binding.soundText.setVisibility(View.GONE);
        }
    }

    private void showCustomBottomSheetDialog() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext());
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.sound_dialog, null);

        bottomSheetDialog.setCanceledOnTouchOutside(false);

        dialogView.findViewById(R.id.import_audio).setOnClickListener(v -> onImportAudioClicked(bottomSheetDialog));
        dialogView.findViewById(R.id.create).setOnClickListener(v -> onCreateClicked(bottomSheetDialog));
        dialogView.findViewById(R.id.cancel_button).setOnClickListener(v -> bottomSheetDialog.dismiss());

        bottomSheetDialog.setContentView(dialogView);
        bottomSheetDialog.show();
    }

    private void onImportAudioClicked(BottomSheetDialog bottomSheetDialog) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            openAudioPicker();
        } else {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(requireActivity(),
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_READ_MEDIA_AUDIO);
            } else {
                openAudioPicker();
            }
        }
        bottomSheetDialog.dismiss();
    }

    private void onCreateClicked(BottomSheetDialog bottomSheetDialog) {
        Intent intent = new Intent(getActivity(), RecordActivity.class);
        startActivity(intent);
        bottomSheetDialog.dismiss();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_READ_MEDIA_AUDIO:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAudioPicker();
                } else {
                    Toast.makeText(requireContext(), "Permission denied to read your audio files", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void openAudioPicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("audio/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE_PICK_AUDIO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode != REQUEST_CODE_PICK_AUDIO || resultCode != RESULT_OK || data == null) {
            return;
        }

        audioUri = data.getData();
        if (audioUri == null) {
            Toast.makeText(requireContext(), "The file could not be found.", Toast.LENGTH_LONG).show();
            return;
        }

        fileName = HappySoundUtil.getFileName(audioUri, requireActivity());

        try {
            happyViewModel.getCountAsync(audioUri.toString(), new HappyRepository.CountCallback() {
                @Override
                public void onCountFetched(int count) {
                    if (count > 0) {
                        Toast.makeText(requireContext(), "This file has been imported and cannot be imported again", Toast.LENGTH_LONG).show();
                    } else {
                        happyViewModel.insert(new HappyData(fileName, audioUri.toString(), fileName, audioUri.toString(), "", false, true));
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "Failed to insert database: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onItemSwiped(int position) {
        deleteItem(position);
    }

    public void deleteItem(int position) {
        HappyData happyData = happyDataList.get(position);
        try {
            happyViewModel.delete(happyData);
            Toast.makeText(getContext(), "Sound deleted successfully.", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getContext(), "Failed to delete sound.", Toast.LENGTH_SHORT).show();
        }
    }

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