package com.ar.artraceartpro.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ar.artraceartpro.data.local.entity.ImageData;
import com.ar.artraceartpro.databinding.FragmentImportBinding;
import com.ar.artraceartpro.topon.AdManager;
import com.ar.artraceartpro.topon.onActionListener;
import com.ar.artraceartpro.ui.adapter.ImageRecyclerViewAdapter;
import com.ar.artraceartpro.utils.ImportUtils;
import com.ar.artraceartpro.utils.ItemDecoration;
import com.ar.artraceartpro.viewmodel.ImageViewModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class ImportFragment extends Fragment {

    private static final int PICK_IMAGE_REQUEST_CODE = 202;
    private FragmentImportBinding binding;
    private ImageRecyclerViewAdapter adapter;
    private final List<String> imagePaths = new ArrayList<>();
    private ImageViewModel imageViewModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentImportBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        imageViewModel = new ViewModelProvider(requireActivity(), new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication()))
                .get(ImageViewModel.class);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new ImageRecyclerViewAdapter(new ArrayList<>(), requireContext(), requireActivity(), 1, new ArrayList<>());
        binding.recyclerView.setAdapter(adapter);

        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.recyclerView.addItemDecoration(itemDecoration);

    }

    private void initEvent() {

        binding.add.setOnClickListener(v -> {
            AdManager.showTopOn(requireActivity(), new onActionListener() {
                @Override
                public void onAction() {
                    openImagePicker();
                }
            });
        });

        loadAllImportImage();
    }

    private void loadAllImportImage() {
        imageViewModel
                .getAllImportLive()
                .observe(getViewLifecycleOwner(), new Observer<List<ImageData>>() {
                    @Override
                    public void onChanged(List<ImageData> imageEntries) {
                        if (imageEntries.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateData(imageEntries);
                    }
                });
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST_CODE) {
            requireActivity();
            if (resultCode == Activity.RESULT_OK && data != null) {
                Uri selectedImageUri = data.getData();
                if (selectedImageUri != null) {
                    try {
                        if (ImportUtils.isImageSizeValid(selectedImageUri, requireContext())) {
                            ImportUtils.saveImage(selectedImageUri, imagePaths, imageViewModel, requireContext(), requireActivity());
                        } else {
                            Toast.makeText(getContext(), "The image size is out of limit", Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "Could not get image size: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }


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