package com.ardrawing.ardrawingspace.activity;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.ardrawing.ardrawingspace.R;
import com.ardrawing.ardrawingspace.adapter.SpaceRecyclerViewAdapter;
import com.ardrawing.ardrawingspace.databinding.ActivityCategoryBinding;
import com.ardrawing.ardrawingspace.room.SpaceEntity;
import com.ardrawing.ardrawingspace.util.ItemDecoration;
import com.ardrawing.ardrawingspace.viewmodel.SpaceViewModel;

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

public class CategoryActivity extends AppCompatActivity {
    private ActivityCategoryBinding binding;
    private SpaceRecyclerViewAdapter adapter;
    private SpaceViewModel viewModel;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityCategoryBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initData();
        initEvent();
    }

    private void initData() {
        String path = getIntent().getStringExtra("imagePath");
        if (path == null) {
            finish();
            return;
        }

        String[] parts = path.split("/");
        title = parts[0].split("_")[1];

        viewModel = new ViewModelProvider(this).get(SpaceViewModel.class);

        binding.recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        adapter = new SpaceRecyclerViewAdapter(this, new ArrayList<>(), 2);
        binding.recyclerView.setAdapter(adapter);

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

    private void initEvent() {
        binding.back.setOnClickListener(v -> finish());
        binding.text.setText(title);
        loadImage();
    }

    private void loadImage() {
        viewModel
                .getEntityByImagePath(title)
                .observe(this, spaceEntityList -> {
                    adapter.updateItems(spaceEntityList);
                });
    }

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