package com.ardraw.ardrawingflow.ui.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.ardraw.ardrawingflow.callback.DeleteCallback;
import com.ardraw.ardrawingflow.data.database.entity.FlowData;
import com.ardraw.ardrawingflow.databinding.FragmentAddBinding;
import com.ardraw.ardrawingflow.ui.adapter.FlowItemAdapter;
import com.ardraw.ardrawingflow.ui.viewmodel.FlowViewModel;
import com.ardraw.ardrawingflow.util.UploadUtil;
import com.ardraw.ardrawingflow.util.ItemDecoration;

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

public class AddFragment extends Fragment implements DeleteCallback {
    private static final int PICK_IMAGE_REQUEST_CODE = 202;
    private FragmentAddBinding binding;
    private FlowItemAdapter adapter;
    private FlowViewModel flowViewModel;
    private final List<String> imagePaths = new ArrayList<>();

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

        initData();
        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        flowViewModel = new ViewModelProvider(this).get(FlowViewModel.class);

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

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

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

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

        loadAllImportImage();
    }

    private void loadAllImportImage() {
        flowViewModel
                .getAddLiveData()
                .observe(getViewLifecycleOwner(), new Observer<List<FlowData>>() {
                    @Override
                    public void onChanged(List<FlowData> flowDataList) {
                        if (flowDataList.isEmpty()) {
                            binding.text.setVisibility(View.VISIBLE);
                        } else {
                            binding.text.setVisibility(View.GONE);
                        }
                        adapter.refreshItems(flowDataList);
                    }
                });
    }

    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.saveImage(imageUri, imagePaths, flowViewModel, requireContext());
        } else {
            Toast.makeText(getContext(), "The image size is out of limit", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDelete(FlowData flowData) {
        UploadUtil.deleteImage(flowData, flowViewModel, requireContext());
        loadAllImportImage();
    }

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