package com.ardrawing.ardrawingspace.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

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

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

import com.ardrawing.ardrawingspace.adapter.SpaceRecyclerViewAdapter;
import com.ardrawing.ardrawingspace.databinding.FragmentImportBinding;
import com.ardrawing.ardrawingspace.room.SpaceEntity;
import com.ardrawing.ardrawingspace.util.DeleteCallback;
import com.ardrawing.ardrawingspace.util.ItemDecoration;
import com.ardrawing.ardrawingspace.util.UploadUtil;
import com.ardrawing.ardrawingspace.viewmodel.SpaceViewModel;

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

public class ImportFragment extends Fragment implements DeleteCallback {
    private static final int PICK_IMAGE_REQUEST_CODE = 202;
    private FragmentImportBinding binding;
    private SpaceRecyclerViewAdapter adapter;
    private SpaceViewModel viewModel;
    private final List<String> imagePaths = new ArrayList<>();

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

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        viewModel = new ViewModelProvider(this).get(SpaceViewModel.class);

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

        adapter = new SpaceRecyclerViewAdapter(requireContext(), new ArrayList<>(), 1);
        binding.recyclerView.setAdapter(adapter);
        adapter.setDeleteCallback(this);

        binding.recyclerView.addItemDecoration(new ItemDecoration(35, 15, 20));
    }

    private void initEvent() {
        binding.upload.setOnClickListener(v -> {
            openImagePicker();
        });

        loadAllImportImage();
    }

    private void loadAllImportImage() {
        viewModel
                .getImportLiveData()
                .observe(getViewLifecycleOwner(), new Observer<List<SpaceEntity>>() {
                    @Override
                    public void onChanged(List<SpaceEntity> spaceEntityList) {
                        if (spaceEntityList.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.updateItems(spaceEntityList);
                    }
                });
    }

    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 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                processImage(selectedImageUri);
            }
        }
    }

    private void processImage(Uri imageUri) {
        if (UploadUtil.isImageSizeValid(imageUri, requireContext())) {
            UploadUtil.saveImageByPath(imageUri, imagePaths, viewModel, requireContext());
        } else {
            Toast.makeText(getContext(), "The image size is out of limit", Toast.LENGTH_SHORT).show();
        }
    }

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

    @Override
    public void onDelete(SpaceEntity entity) {
        UploadUtil.deleteImageByPath(entity, viewModel, requireContext());
        loadAllImportImage();
    }
}